Hailwood
Hailwood

Reputation: 92601

How to apply a jQuery event handler to multiple cached selectors?

Lets say I have three buttons

<button data-action="grow" class="resizeButton">Grow</button>
<button data-action="shrink" class="resizeButton">Shrink</button>
<button id="normalButton">Normal Button</button>

I have the buttons in variables

var $normalButton = $('#normalButton');
var $growButton = $('.resizeButton[data-action="grow"]');
var $shrinkButton = $('.resizeButton[data-action="shrink"]');

Now lets say I want to hook up a mouseenter, mouseleave, and click event handler to the normal button

$normalButton.on({
   mouseenter: function(){
       //do some stuff
   },

   mouseleave: function(){
       //reverse some stuff
   },

   click: function(){
       //do some more stuff
   }
});

The magical jQuery wizards make this work for us.

Now lets say we want to append a mouseenter, mouseleave, and click event handler to the grow button and the shrink button. The same handlers for those buttons, but different handlers to the normal button.

There are a couple of ways I can see to do this, but they are all basically the same idea, just assign them twice, once to the first button, once to the next button.

So,

var handlers = {
    mouseenter: function(){
        //do some different stuff
    },

    mouseleave: function(){
        //reverse some different stuff
    },

    click: function(){
        //do some more different stuff
    }
};

$growButton.on(handlers);
$shrinkButton.on(handlers);

or

$.each([$growButton, $shrinkButton], function(i, el){
    el.on({
        mouseenter: function(){
            //do some different stuff
        },

        mouseleave: function(){
            //reverse some different stuff
        },

        click: function(){
            //do some more different stuff
        }
    });
});

But what I am wondering is if there is a syntax to create a jQuery object from, or just apply the handlers to a group of cached Selectors like $([$growButton, $shrinkButton]).on(... or similar?

Upvotes: 2

Views: 677

Answers (1)

Ram
Ram

Reputation: 144699

You can use add method:

$growButton.add($shrinkButton).on(...)

Upvotes: 8

Related Questions