Home > Back-end >  jQuery event listener fires before selector applied
jQuery event listener fires before selector applied

Time:06-25

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  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 :D

CodePudding user response:

You can always just use the jquery dblclick event. Jquery dblclick

$(document).on("dblclick",".btn-delete",function(){      
  console.log("DELETE");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button >DELETE</button>

CodePudding user response:

@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  src="https://kns.im/include/img/plus.png" style="width:50px">

  • Related