In my HTML here
$(document).click(function(){
alert('Document Clicked');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button type='button'>CLICK [NO ALERT]</button>
<button type='button'>ME[NO ALERT]</button>
</body>
In my code here, How do I prevent the alert from showing up if I clicked on the buttons, But anything except the buttons can be alerted.
You can add another click
listener on that specific <button>
and stop the propagation of the event:
$(document).click(function(){
alert('Document Clicked');
})
$('.not-clickable').click(function(e) {
e.stopPropagation();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button type='button'>CLICK [NO ALERT]</button>
<button type='button' class="not-clickable">ME[NO ALERT]</button>
</body>
Another option is to check if the element that was clicked is that specific button:
$(document).click(function(e){
if (e.target.classList.contains('not-clickable')) {
return;
}
alert('Document Clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button type='button'>CLICK [NO ALERT]</button>
<button type='button' class="not-clickable">ME[NO ALERT]</button>
</body>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With