Skip to content

Instantly share code, notes, and snippets.

@halilim
Last active August 29, 2015 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halilim/7b48d47c589f24c9d218 to your computer and use it in GitHub Desktop.
Save halilim/7b48d47c589f24c9d218 to your computer and use it in GitHub Desktop.
jQuery easyHide plugin - a simple plugin to hide stuff by clicking anywhere on the document (other than the element) or by hitting ESC.
;(function ($) {
$.fn.easyHide = function (opts) {
opts = opts || {};
opts["hideFn"] = opts["hideFn"] || function () {
this.hide();
};
return this.each(function () {
var $this = $(this);
if (opts["onDocClick"] !== false) {
$(document).click(function (e) {
if (e.target != $this[0] && !$.contains($this[0], e.target)) {
opts["hideFn"].call($this);
}
});
}
if (opts["onEsc"] !== false) {
$this.keyup(function (e) {
if (e.keyCode == 27) {
opts["hideFn"].call($this);
}
});
}
});
};
})(jQuery);
<form method="GET" action="search">
<input placeholder="Enter keyword &hellip;" name="q" type="text" style="display:none">
<button type="submit">Search</button>
</form>
<script>
var $form = $("form"), $inp = $form.find("input[type=text]");
$form.find("button").on("click", function (e) {
if ($inp.is(":hidden")) {
$inp.slideDown("fast").focus();
e.preventDefault();
}
});
$form.easyHide({
hideFn: function () {
$inp.slideUp("fast");
}
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment