Robert Bue
Robert Bue

Reputation: 1914

Bind multiple events to same function

How can I bind mutiple events to the same function. I want click and touchstart to do the same. And then I want a second function for mouseover. I would like to use this kind of setup:

    $(document).on({
        click: function (event) {
        // I want this: click, touchstart: function (event) {
            event.preventDefault();
            // do something         
        },
        mouseover: function (event) {
            event.preventDefault();
            // do something         
        }
    }, '.link');

Upvotes: 2

Views: 537

Answers (3)

nnnnnn
nnnnnn

Reputation: 150010

According to the .on() documentation (and confirmed via a quick look at the .on() implementation) you could do this:

$(document).on({
    "click touchstart" : function (event) {
        event.preventDefault();
        // do something         
    },
    mouseover: function (event) {
        event.preventDefault();
        // do something         
    }
}, '.link');

Demo: http://jsfiddle.net/XzkTm/

Upvotes: 0

Adrian Wragg
Adrian Wragg

Reputation: 7401

There's no reason why you can't call an external function instead:

function myExternalFunction (event) {
    // do stuff
}

$(document).on({
    click: myExternalFunction,
    mouseover: myExternalFunction
}, '.link');

Upvotes: 1

techfoobar
techfoobar

Reputation: 66663

You can combine the events in one .on() with space:

$(document).on('click touchstart', function(e) {
    // this will be called on click as well as touchstart
});

Upvotes: 2

Related Questions