Skip to content

Instantly share code, notes, and snippets.

@nekman
Last active December 23, 2015 19:59
Show Gist options
  • Save nekman/6686116 to your computer and use it in GitHub Desktop.
Save nekman/6686116 to your computer and use it in GitHub Desktop.
/**
* jQuery plugin that can be used as a shortcut
* to stop JS-events from bubbling.
*
* See this stackoverflow post for more information:
* http://stackoverflow.com/questions/18968847/stop-js-event-propagation-on-table-row-click/
*
* Usage:
* - Add the attribute or class "no-bubble" to a element.
* <button no-bubble /> or <button class="no-bubble" />
*
* Advanced usage:
* - Call the stopPropagation method on a jQuery object:
*
* $(selector).stopPropagation(events);
*
* @param (String) events = (optional) event names separated by space.
*
* Examples:
*
* $(selector).stopPropagation(); //Prevents propagation for click events.
* $(selector).stopPropagation('click keydown'); //Prevents propagation for click and keydown events.
*/
(function($) {
'use strict';
/**
* Stop the event from bubbling up the DOM-tree.
*
* @param {String events} (optional, default 'click') - The event that we should stop propagation for.
*/
$.fn.stopPropagation = function(events) {
//TODO: May need to call the off event first, but this will also remove previous events...
return this.on(events || 'click', function(e) {
e && e.stopPropagation();
return true;
});
};
/**
* Stop the event from bubbling up the DOM-tree.
* Searches for nodes with "no-bubble" attribute, and nodes with .no-bubble class.
*
* @param {String events} (optional, default 'click') - The event that we should stop propagation for.
*/
$.stopPropagation = function(events) {
$('*[no-bubble]')
.add('.no-bubble')
.stopPropagation(events);
};
// init
$(function() {
$.stopPropagation();
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment