Skip to content

Instantly share code, notes, and snippets.

@vaclavbohac
Created August 13, 2012 22:32
Show Gist options
  • Save vaclavbohac/3344541 to your computer and use it in GitHub Desktop.
Save vaclavbohac/3344541 to your computer and use it in GitHub Desktop.
Inline handler example
/*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));
<!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