mouseclick outside a DOM element

submit to reddit

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.

example in js (jQuery):

var clickOverThePanel = false;
var clickOverTheBody = false;

$('#the-panel').click(function() {
    clickOverThePanel = true;
});

$(document).click(function() {
    clickOverTheBody = true;

    if (clickOverTheBody && !clickOverThePanel)
        $('#the-panel').hide();

});

Where’s the solution

Well when you click over the panel you get both document and panel click events registered, and you always get the document.click event. In such way you know that the click somewhere is registered, the only thing is to get if there’s a click over the panel, and that’s why you need the check for !clickOverThePanel. Than you finally know if the user has clicked (true), but has not clicked over the panel (false).

Related posts:

  1. cancel bubbling on element click with jQuery
  2. Remove DOM Element with JQuery
  3. jquery check for element existence in the DOM

You are a GREAT developer? Click here to answer the weekly quiz!

This entry was posted in javascript, micro tutorial and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">