How to Stop Events Bubbling in Jquery

How to stop events bubbling in jQuery?

According to jQuery's documentation:

$('myclass').bind('amodaldestroy'), function(event) {
....does something....
event.stopPropagation();
});

jQuery prevent all event bubbling

It looks like there's no good way to do it with jQuery as it is, but it's very easy to write a new function to allow this.

First I wrote a new function to stop the event from bubbling(, and also log the event why not).

function    eventWrapper(event){

var logString = 'Event called: ' + event.type + ":" + event.namespace;

if (jQuery.isFunction(this.log) == true) {
this.log(logString);
}
else if (jQuery.isFunction(Logger.log) == true) {
Logger.log(logString);
}
else{
console.log(logString);
}

event.stopPropagation();
}

And now a new function that is added to jQuery.

// A global GUID counter for objects
guidWrapper: 1,

proxyWrapper: function(wrappedFn, fn, context, wrapFn ) {

var args, proxy, tmp;

if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}

// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}

// Simulated bind
args = core_slice.call( arguments, 3 );
proxy = function() {
wrappedFn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};

// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;

return proxy;
},

And then instead of binding the function like this:

$(this.element).bind('click', $.proxy(this.click, this));

Instead bind it like this.

$(this.element).bind('click', $.proxyWrapper(eventWrapper, this.click, this));

This means that when the event is triggered, the first element that is listening for that event will call event.stopPropagation on the event, and so it won't bubble up to other elements that may also be listening for that event.

How to stop event bubbling with jquery live?

The short answer is simply, you can't.

The problem

Normally, you can stop an event from "bubbling up" to event handlers on outer elements because the handlers for inner elements are called first. However, jQuery's "live events" work by attaching a proxy handler for the desired event to the document element, and then calling the appropriate user-defined handler(s) after the event bubbles up the document.

Bubbling illustration

(source: shog9.com)

This generally makes "live" binding a rather efficient means of binding events, but it has two big side-effects: first, any event handler attached to an inner element can prevent "live" events from firing for itself or any of its children; second, a "live" event handler cannot prevent any event handlers attached directly to children of the document from firing. You can stop further processing, but you can't do anything about processing that has already occurred... And by the time your live event fires, the handler attached directly to the child has already been called.

Solution

Your best option here (so far as I can tell from what you've posted) is to use live binding for both click handlers. Once that's done, you should be able to return false from the .MoreAppointments handler to prevent the .DateBox handler from being called.

Example:

$('.MoreAppointments').live('click', function(e) 
{
alert("Hi");
return false; // prevent additional live handlers from firing
});

// use live binding to allow the above handler to preempt
$('#CalendarBody .DateBox').live('click', function(e)
{
AddApointment(this);
});

How to prevent jQuery event from bubbling when removing element?

You have to get your event object from the click() callback. If you look at the jquery hide() api docs, the complete callback doesn't get passed anything so your event is undefined, but the click() handler on the other hand gets passed the event object. So you just need to change your javascript to:

$('span.remove').on('click', function(event) {
event.stopPropagation();
$(this).parent().hide(500, function() {
$(this).parent().remove();
});
});

The reason however that the whole list gets removed is another issue. You reference parent() twice targeting the ul to be removed, so just get rid of one of the parents (the scope of $(this) changes to the parent in the hide callback). With this edit the code is:

$('span.remove').on('click', function(event) {
event.stopPropagation();
$(this).parent().hide(500, function() {
$(this).remove();
});
});

It's true however that the propagation of the event, doesn't really have anything to do with the ul being hidden as a whole so you can just remove the event.stopPropagation() line. Final code being:

$('span.remove').on('click', function() {
$(this).parent().hide(500, function() {
$(this).remove();
});
});

jQuery event capturing stop propagation

As you said, jQuery doesn't support listening to events in the capturing phase; you'll have to use standard Javascript instead of jQuery in order to accomplish that. For example:

const parent = document.querySelector('#parent');parent.addEventListener('click', (e) => {  if (e.target.matches('#child')) return;  e.stopPropagation();  console.log('parent was clicked, but not on child');}, true);function myFunction(event){   console.log('child was clicked on');   // when this is clicked, #parent .on(click) also triggers, i don't want that}
<div id="parent" class="areatext">  parent  <div id="input" contenteditable="true" style="min-height:26px;" onkeyup="checkTyping()"></div>  <div id="child" onclick="myFunction()">child</div></div>

How to stop event bubbling in JavaScript?

child is a collection of elements (array)...
you have to loop trough it:

for(var i=0; i<child.length; i++){
child[i].addEventListener("click", function(e) {
if(e.stopPropagation){e.stopPropagation();}else{e.cancelBubble=true;}
}, false);
}

How to stop event bubbling in jquery.

This is happend because modal is child element of overlay, and you hide it's parent element (.abovepage) on click so it hides modal too. One solution is this:

$(document).ready(function () {    //when .modals is clicked     $(".modals").click(function () {        //.abovepage should appear        $(".abovepage").show();        $(".pagecontent").show('slow');    });    $(".abovepage").click(function () {        $(".pagecontent").hide();        $(this).hide();    });});
#maincontent {    height:60px;}#innercontent {    height:40px;    margin:10px;}.modals {    height:40px;    background-color: #6596EE;    border:solid 1px #3B7EF7;    border-radius: 3px;}.modals a {    text-decoration: none;    font-weight: bold;    font:16px arial;    color: white;}.modals:hover {    background: #122A55;}.abovepage {    position:fixed;    left:0;    top:0;    right:0;    bottom:0;    background-color: #3D3C3C;    opacity: 0.6;    display:none;}.pagecontent {    height:100px;    margin-top: 52px;    margin-bottom: 30px;    display:none;}.large {    width:900px;    margin-left: 230px;    margin-right: 222px;}.small {    width:250px;    margin-left: 511px;    border-radius: 3px;}.element {    height:100px;    background-color: white;    box-shadow:3px 3px 8px 3px #030303;    position:relative;    top:0px;    left:0px;    border:solid 1px #1D1B1B;    border-radius: 5px;}.upper {    height:50px;    border-bottom: solid 1px #D3C8C8;}.lower {    height:50px;}.uppercontent {    height:25px;    padding-top: 15px;    padding-left: 14px;    padding-right: 9px;    font-weight:bold;    font:18px arial;}.lowercontent {    height:25px;    padding-top: 15px;    padding-left: 14px;}#closebutton {    float:right;}#closebutton a {    text-decoration:none;    color:#C4BBBB;    font-weight: bold;    font-size:18px;}#closebutton a:hover {    color:#333232;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><body id="wholepage">    <div id="maincontent">        <div id="innercontent">            <button class="modals" data-id="large"><a href="#">Large Modal</a>            </button>            <button class="modals" data-id="small"><a href="#">Small Modal</a>            </button>        </div>    </div>    <div class="abovepage"></div> <!-- here close div -->        <div class="pagecontent large">            <div class="element" data-clicked="no">                <div class="upper">                    <div class="uppercontent" data="modal">Large Modal <span id="closebutton"><a href="#">x</a></span>
</div> </div> <div class="lower"> <div class="lowercontent">...</div> </div> </div> </div>

jQuery how to stop triggered click event from bubbling

You need to have a bound event to the child elements:

$('.panel-select').click(function() {
$(this).children('input').trigger('click');
});

// try adding to the below event not on the parent.

$('.panel-select input').click(function(e) {
e.stopPropagation();
});

Ending JQuery Event Bubbling

stopPropagation does exactly what it sounds like, it stops events from propagating up to the parent elements higher up in the DOM.

It does not stop animations, that would be stop();

$('.sidebar nav ul li').not('.user').click(function(){

$('.sidebar nav ul li').stop(true, true)
.css('background-size', '15px')
.removeClass('active');

$(this).animate({
'background-size': '100%'
}, 500, function() {
$(this).addClass('active');
});
});


Related Topics



Leave a reply



Submit