Skip to content
Advertisement

jQuery event listener fires before selector applied

I am trying to make a system that would require an admin to click a delete button twice before it fires the action. if he focusout of the button, it resets.

$(".unarmed").css("filter", "grayscale(1)").removeClass("armed").click(function(e) {
  $(this).css("filter", "").removeClass("unarmed").addClass("armed");
}).mouseout(function() {
  $(this).css("filter", "grayscale(1)").removeClass("armed").addClass("unarmed");
});

$("body").on("click", ".armed", function() {
  alert("boom");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="unwait unarmed" src="plus.png">

I’ve seen jQuery event listener fires before selector applied? but adding e.stopPropagation() causes the second click to not fire.

when e.stopPropagation() is not in the code, it does fire the second click, but together with the first click (i think this means the problem is not with the second click selector)

here is a fiddle with e.stopPropagation(): https://jsfiddle.net/3jyr72t6/

also, if you have suggestion for making it prettier, i’m open for suggestions 😀

Advertisement

Answer

@icecub answer as snippet:

$(document).ready(function() {
  $(".unarmed").css("filter", "grayscale(1)");
  $(".unarmed").click(function(e) {
    if ($(this).hasClass("armed")) {
      console.log("boom");
    }
    $(this).css("filter", "").removeClass("unarmed").addClass("armed");
  }).mouseout(function() {
    $(this).css("filter", "grayscale(1)").removeClass("armed").addClass("unarmed");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img class="unwait unarmed" src="https://kns.im/include/img/plus.png" style="width:50px">
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement