'Show an alert when someone clicks on a NON link

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.



Solution 1:[1]

You can try jQuery :not() selector

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

Solution 2:[2]

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>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ember
Solution 2 Sumit Sharma