gFontaniva
gFontaniva

Reputation: 903

JQuery cancel others event

I had a buton in my code and I need stop others event clicks on this button, but I need the other events still binded.

The code:

var cancel = true;

$("#btn").on("click", function(ev) { 
    console.log("FIRST CLICK");
});

$("#btn").on("click", function(ev) { 
    console.log("SECOND CLICK");
    if(cancel) {
       --- cancel first click---
    }
});

The usage:

cancel = true;
$("#btn").click();
cancel = false;
$("#btn").click();

Expected output:

SECOND CLICK

FIRST CLICK
SECOND CLICK

I already try

ev.stopImmediatePropagation(); 
ev.stopPropagation();
ev.preventDefault(); 
return false;

but any of this work, how I stop all other click events binded without unbind?

Upvotes: 1

Views: 1200

Answers (2)

NotanNimda
NotanNimda

Reputation: 407

The .off jquery method is the way to go i think

$("#btn").on("click", function(ev) { 
console.log("FIRST CLICK");
});

$("#btn").on("mousedown", function(ev) { 
console.log("SECOND CLICK");
--- cancel first click---
$("#btn").off('click');
$("#btn").text("Anything you want to do");
// then if you need to rebind you can do 
$("#btn").on("click", function(ev) { 
console.log("FIRST CLICK");
});
});

So you unbind it run the code rebind it. But i think the answer to your problem is that `$(function(){

var cancel= 'true';
$("#btn").on("click",function(e){
             if(cancel == 'true'){
    cancel = 'false';
}else{
    cancel = 'true';
}
             });

});

Sorry for the indentation but this will switch cancel to on/off I think that was the goal intended. When you click on the button it will switch for false to true or true to false.

Upvotes: 3

Chris Thorsvik
Chris Thorsvik

Reputation: 470

One solution is to carefully mind the order that events are bound. By binding the more important click first, we can stopImmediatePropagation() to cancel any subsequent bindings.

$("#btn").on("click", function(e) {
  e.stopImmediatePropagation();
  console.log("Reversed second click");
});
$("#btn").on("click", function(e) {
  console.log("Reversed first click");
});

$("#btn").on("click", function(e) {
  console.log("First click");
});
$("#btn").on("click", function(e) {
  e.stopImmediatePropagation();
  console.log("Second click");
});

$("#btn2").on("click", function(e) {
  e.stopImmediatePropagation();
  console.log("Reversed second click");
});
$("#btn2").on("click", function(e) {
  console.log("Reversed first click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">
  Something
</button>
<button id="btn2">
  Reversed Order
</button>

Upvotes: 2

Related Questions