panthro
panthro

Reputation: 24061

Stop button clicks?

I have two methods

$('.btn-delete').click(function(){

        //do A
        //return false?
    });

$('.btn-delete').click(function(){

        //do B
    });

How can I stop 'B' from happening when A returns false?

Upvotes: 1

Views: 75

Answers (5)

Adil
Adil

Reputation: 148110

You better make a single function and put condition to handle if that is not the solution you can set a flag in first event.

Using single event handler

$('.btn-delete').click(function(){

    //do A
    if(condition != false)
        execute code of second event.
    //return false?

});

Using flag

flag = true;
$('.btn-delete').click(function(){    
        //do A
        if (something) {
           flag = true;
        else
           flag = false;
    return flag;  
 });

$('.btn-delete').click(function(){
        if(!flag) return;
        //do B
});

Upvotes: 1

Oriol
Oriol

Reputation: 287980

(Just in case anyone wants a non-jQuery solution).


This can't be done directly in plain JavaScript, because you can't be sure in which order the event listeners will be triggered.

According to the spec,

Although all EventListeners on the EventTarget are guaranteed to be triggered by any event which is received by that EventTarget, no specification is made as to the order in which they will receive the event with regards to the other EventListeners on the EventTarget.

Then, one possibility is joining all handlers inside only one function.

But if that's not possible, you could use event delegation to a wrapper, and stop propagation if necessary:

<div class="btn-wrapper"><button class="btn-delete">Delete</button></div>

­

var btn = document.querySelector('.btn-delete');
btn.addEventListener('click', function(e){
    // do A
    if(cond) e.stopPropagation();
}, false);
btn.parentNode.addEventListener('click', function(e){  
    //do B
}, false);

Upvotes: 0

Sergey Yarotskiy
Sergey Yarotskiy

Reputation: 507

Why not to put altogether?

$('.btn-delete').click(function(){

    //do A
    // if true do B
});

Upvotes: 2

Rui
Rui

Reputation: 4886

Use the jquery event's stopImmediatePropagation. That's exactly what it's for:

$('.btn-delete').click(function(e){

        //do A
        if (a is returning false) 
          e.stopImmediatePropagation();
    });

$('.btn-delete').click(function(){

        //do B
    });

Upvotes: 2

mimipc
mimipc

Reputation: 1374

var whatDoesAReturn = false;
$('.btn-delete').click(function(){
    if (something) {
        whatDoesAReturn = true;
        return true;
    } else {
        whatDoesAReturn = false;
        return false;
    }
});

$('.btn-delete').click(function(){
    if (!whatDoesAReturn) {
        // Do whatever
    }
});

Upvotes: 2

Related Questions