Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save geraldfullam/083cf341ff8985946e5b to your computer and use it in GitHub Desktop.
Save geraldfullam/083cf341ff8985946e5b to your computer and use it in GitHub Desktop.
Use of :not() in delegated event
<div class="outer">
<div class="inner">
<a href="#">Click once, trigger twice</a>
</div>
</div>
<div class="outer">
<span class="inner">
<button type="button">Click once, trigger thrice</button>
</span>
</div>
$('body').on('click', ':not(a)', function (e) {
var message = '';
message += $(this).prop('tagName');
message += $(this).prop('className') ? '.' + $(this).prop('className') : '';
message += $(this).text() ? ': ' + $(this).text() : '';
$(this).highlight();
alert(message);
});
/* $('selector').highlight();
// source: http://stackoverflow.com/a/13106698/2502532 */
jQuery.fn.highlight = function () {
$(this).each(function () {
var el = $(this);
$("<div/>")
.width(el.outerWidth())
.height(el.outerHeight())
.css({
"position": "absolute",
"left": el.offset().left,
"top": el.offset().top,
"outline": "Lime solid 2px",
"box-shadow": "0 0 10px 2px Lime",
"opacity": ".6",
"z-index": "0"
}).appendTo('body').delay(400).fadeOut(1200).queue(function () { $(this).remove(); });
});
}
body {
font-family: sans-serif;
}
.outer {
margin: 20px;
padding: 20px;
background-color: Tomato;
}
.inner {
display: block;
padding: 20px;
cursor: pointer;
text-align: center;
background-color: PeachPuff;
}

Use of :not() in delegated event

Proof that using :not() in event delegation is honored, but doesn't prevent bubbling and thus potentially triggering the handler multiple times.

A Pen by Gerald on CodePen.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment