Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Onclick on document and not specific element Alert

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.

like image 717
AXAI Avatar asked Sep 16 '17 21:09

AXAI


1 Answers

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>
like image 172
Dekel Avatar answered Oct 16 '22 02:10

Dekel