FlyingCat
FlyingCat

Reputation: 14250

How to bind the same handler to multiple events with jQuery

Just wondering if there are ways to simplify the following script...Thanks for the help.

$('#right-arrow').live('click', function(){
        removt();
        callAjaxToCheck();
        show = true;
})

$('#tab').click(function(){
   removeTut();
   callAjaxToCheck();
   show = true;

})

$('left-arrow').live('click', function(){
        removeT();
        callAjaxToCheck();
        show = true;
})

Upvotes: 2

Views: 625

Answers (3)

sQVe
sQVe

Reputation: 2015

var func = function() {
    "use strict";
    removeTut();
    callAjaxToCheck();
    showTutorial = true;
};

$("#parent").on("click", "#eplanner-view-range-right-arrow, #eplanner-view-range-left-arrow", func);
$("#lesson-search-tab").click(func);

Changed .live() to .on() as .live() is deprecated as of jQuery version 1.7+. If you're running an older version of jQuery don't change .live().

Upvotes: 2

We Are All Monica
We Are All Monica

Reputation: 13336

Always include semicolons in your code. (You're missing them after the }) lines).

I think the cleanest way to do it is to make a separate function:

function doStuff() {
    removeTut();
    callAjaxToCheck();
    showTutorial = true;
}

$('#eplanner-view-range-right-arrow').live('click', doStuff);
$('#lesson-search-tab').click(doStuff);
$('#eplanner-view-range-left-arrow').live('click', doStuff);

Of course, you should use a more descriptive function name than doStuff.

Upvotes: 6

João Silva
João Silva

Reputation: 91299

Use a multiple selector:

$('#eplanner-view-range-right-arrow,#lesson-search-tab,#eplanner-view-range-left-arrow').live('click', function(){
   removeTut();
   callAjaxToCheck();
   showTutorial = true;
});

Upvotes: 2

Related Questions