Created
August 13, 2012 22:32
-
-
Save vaclavbohac/3344541 to your computer and use it in GitHub Desktop.
Inline handler example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*global document, jQuery */ | |
(function ($) { | |
'use strict'; | |
$(document).on('click', 'button', (function () { | |
var labels = ['Edit', 'Apply'], | |
createInput = function (text) { | |
return $('<input type="text">').val(text); | |
}, | |
createSpan = function (text) { | |
return $('<span>').text(text); | |
}; | |
return function (evt) { | |
var $button = $(evt.target), | |
$span = $button.closest('div').find('span'), | |
$input; | |
if ($span.length) { // Replace span with input. | |
$input = createInput($span.text()); | |
$span.replaceWith($input); | |
} else { // Replace input with span. | |
$input = $button.closest('div').find('input'); | |
$input.replaceWith(createSpan($input.val())); | |
} | |
$button.text(labels[$span.length]); | |
evt.preventDefault(); | |
}; | |
}())); | |
}(jQuery)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>Handlers example</title> | |
</head> | |
<body> | |
<section role="user"> | |
<div> | |
<label>Firstname:</label> | |
<span>John</span> | |
<button>edit</button> | |
</div> | |
<div> | |
<label>Lastname:</label> | |
<span>Doe</span> | |
<button>edit</button> | |
</div> | |
</section> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> | |
<script src="js/handlers.js"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment