Francis Forget
Francis Forget

Reputation: 21

Check if a click is made in an entire HTML page containing Javascript

I'm currently developing a Web application that uses HTML and JavaScript. I have a problem related to my comboboxes, and now, what I need is to check if a clicked is pressed in my entire page.

The thing is, when I use JavaScript to check if a click is made, it's not properly checking my JavaScript area.

    $("html").click(function () 
    {
        alert("Click");
    });

I have an area that can be retracted with a - (minus) button that I made, which means it's dynamic. When this area is visible, every time I click on it doesn't count as a click in my HTML page (as the .click doesn't seem to like dynamic stuff).

Do you have an idea on how I can check if a click is made, everywhere in my page except in one place.

So really, what I need, is a way to capture every single click I make, except in one particular DIV in my program.

If this can help you, the boxes that are not recognized by the click are contained in a table and in a tbody. Does this information make it easier to fix?

Upvotes: 0

Views: 1285

Answers (2)

JSchirrmacher
JSchirrmacher

Reputation: 3354

Your function should work for clicks on the whole page.

What you need is a similar click handler which listens on your area. This click handler should return false to prevent the first one to work as well. To bind this click handler even to new, dynamically created DOM elements, use on() with a css selector and create the new elements with a class (e.g. special)

 $(document)
  .on("click", ".special", function () {
    alert("Click on special div");
    return false;
  })
  .on("click", function () {
    alert("Click elsewhere");
  });

See my Fiddle: https://jsfiddle.net/efckqng0/1

Upvotes: 1

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

Give it a class, and check it accordingly, capturing only clicks that don't match that class:

$('html').click(function(e) {   
  if( !$(e.target).hasClass("thisClass") )
 {
  alert("you clicked outside the red!");
 }
});    

Here is the fiddle: http://jsfiddle.net/0nvgdm1j/1/

Upvotes: 1

Related Questions