Tag Archives: click

cancel bubbling on element click with jQuery

When you click over an element

This is easy, on the element can be attached event listener an such event listener is built in as the click event is. It’s simply like that:

<div click="func1()"></div>

This with jQuery

A bit different with jQuery, but with the same effect is:

$('div').click(func1);

When there is a bubbling?

Well, if you just copy paste this code in your page:

$(document).click(function() 
    console.log('clicked on the document');
});
$('div').click(function() 
    console.log('clicked on the div');
});

Note: if you’re using Firefox keep the console.log function, in other case you may replace it with either alert or $.log from the recent jQuery plugin i wrote.

Now if you click over the div element you get both messages, cause there is no bubble canceling. If you’d like to add such canceling, just add this code to the click callback for the div element:

return false;

and now the code should look like:

$(document).click(function() 
    $.log('clicked on the document'); 
});
$('div').click(function() 
    $.log('clicked on the div'); return false;
});

mouseclick outside a DOM element

What if you have to close on outside mouse click?

This situation is kind to be familiar. There is some panel which should be closed on outside click. Yeah, this is the most common usage of the outside click. And to do that is pretty simple.

In this tutorial … jQuery

For those of you not used to use jQuery, in short this is a JavaScript library, which gives you the power to manipulate the DOM with ease. One of the very good parts of jQuery is really the ability to help you with less code to do the hard work of searching and changing the DOM. If you don’t have any experience with this library, well you can use any other if you’d like.

First step: combine the events

One of the events should be click over the panel, and the other click over the document. Continue reading mouseclick outside a DOM element