Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Javascript code on click of anywhere on the page (except on click of certain divs)

I have this piece of Javascript code:

$('#catDIV').on('click',function(){

    $("#dogDIV").fadeOut(500, function() {

            makeCat();

        }).fadeIn(500);
});

This fades out the div “dogDIV”, runs the function “makeCat();” and fades “dogDIV” back in whenever the div “catDIV” is clicked on.

My question is, is it possible to change this code so that it will run no matter what part of the page is clicked on, and is it possible to specify certain divs that shouldn’t activate the code?

In other words, is it possible to say something like “If any part of the page is clicked, except for these particular divs, then run the code…”.

I’d like the code to run no matter where the user clicks on the page, but I don’t want it to run if the user clicks on the div “catDIV” or another div called “mouseDIV”. I’m not sure if this is possible?

I've seen this similar question: jQuery click anywhere in the page except on 1 div But is it possible to specify multiple divs that shouldn't trigger the code to run?

Any help with this would be really appreciated, thank you in advance!

like image 654
Emily Avatar asked Dec 06 '25 02:12

Emily


2 Answers

Handle click on document, #catDIV and #mouseDIV. Do nothing on click on the latter two. The click on any other element will bubble up to the document's click handler.

    $(document).click(function(evt) {
      alert("clicked anywhere except catDIV and mouseDIV");
    });
    $("#catDIV, #mouseDIV").click(function(evt) {
      evt.stopPropagation();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="catDIV">catDIV</div>
<div id="cowDIV">cowDIV</div>
<div id="mouseDIV">mouseDIV</div>
like image 160
Amadan Avatar answered Dec 08 '25 15:12

Amadan


there are several ways you could do that, the simplest would be to use multiple '||' (or) statements if the div id's are fixed in advance.

$('body').click(function(evt) {    
   if (evt.target.id == "example" || evt.target.id == "example2") {
        return;
   }
   $("#dogDIV").fadeOut(500, function() {
        makeCat();
    }).fadeIn(500);
});

Alternatively, you could tag all the divs you don't want to activate the event with a class and check the event handler for the class instead.

EDIT: for the latter, the code would be

if ($(evt.target).attr('class') == 'exampleClass')
like image 34
Jonah Williams Avatar answered Dec 08 '25 17:12

Jonah Williams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!