views:

32

answers:

3

I know this is probably a very simple fix. I need to use 2 variables for this function and with the current code it only fires on the first variable. Variables MUST be used for the function in question.

var a = $(h1), b = $(h2); 

    $(a, b).hover(function(){
        ...stuff happens here
    });

please DO NOT suggest something like the scenario below. variables NEED to be used.

$('h1, h2').hover(function(){...});
+1  A: 
a.hover(myHover);
b.hover(myHover);

function myHover(){
     alert('i wish you a happy hovering!');
}

the second parameter of the $ function defines the dom chunk for the search, if you leave it out it takes the hole document. so you better don't mess with, if you are trying to get all your elements on the page

antpaw
+1  A: 

If for whatever reason you must work with separately assigned variables representing jQuery collections, you can add them:

var a = a.add(b);
$(a).hover(...

Also, don't forget you probably want $('h1'), not $(h1).

Here's a working fiddle.

Ken Redler
Corrected -- should be `.add()`, not `.merge()`.
Ken Redler
+5  A: 

You don't need to wrap the variables with jQuery initially.

Assuming h1 and h2 represent DOM nodes:

$([h1, h2]).hover(function(){
    ...stuff happens here
});

We are passing an array as the jQuery function accepts an array of DOM elements. See docs.

See examples.

Anurag