Onclick on a document, not a specific Alert element

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>
Run codeHide result

In my code here, How to prevent a warning from appearing if I pressed buttons, But nothing but buttons can be warned.

+6
source share
3 answers

You can add another clicklistener on this particular one <button>and stop the event propagation:

$(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>
Run codeHide result

Another option is to check if the item that was clicked is this particular 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>
Run codeHide result
+6
source

try

$("#SomeElementId").click(function(e) {
   //do something
   e.stopPropagation();
})
Run codeHide result
0
source

<button type='button' onclick="event.stopPropagation()">CLICK [NO ALERT]</button>. click , event.stopPropagation(), .

0

All Articles