Home > OS >  Show an alert when someone clicks on a NON link
Show an alert when someone clicks on a NON link

Time:05-13

This is what I try to do.

To show an alert to those who click on any part of the page, not in a link

I try this but the alert appears when links are clicked too.

$('body').click(function(){
   alert('Nothing to click here!');
});

I need to exclude links from function, but I don't know how.

CodePudding user response:

You can try jQuery :not() selector

$('body:not(a)').click(function(){
   alert('Nothing to click here!');
});

CodePudding user response:

You can use isSameNode() or contains() function in this case.

$("body").click(function(event){
    if(
        document.getElementById("foo").isSameNode(event.target) 
        || document.getElementById("foo").contains(event.target)
    ){
    alert('Click event triggered from inside of <a> element');
        return;
    }
    alert('Click event triggered from outside of <a> element');
});
body {
width:100px;
height:100px;
border: 1px solid black;
}

#foo {
background-color:red;
}
<script
  src="https://code.jquery.com/jquery-3.6.0.min.js"
  integrity="sha256-/xUj 3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
  crossorigin="anonymous"></script>

<body>
<a id="foo">Hello World!!</a>
</body>

  • Related