2

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?

1 Answer 1

8

You can use add method:

$growButton.add($shrinkButton).on(...)
Sign up to request clarification or add additional context in comments.

2 Comments

Adding to this, you may want your code more dynamically, for example, push all elements into an array and then apply the event to all of them. You can: simply use $( arrayOfJqueryObjects ).
@gustavohenke Why would you do that when you can just use add? Use something like var jqObjs = $("#el1"); jqObjs.add($("#el2")); jqObjs.add($("#el3")); - where, of course, the individual things passed to add would be existing jQuery objects in this case. It's much more maintable than dealing with an array as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.