Reputation: 4239
I am trying to assign hover event to 2 elements at the same time. Are there better ways to do this?
//I want to assign hover to another element.
$element1=$('hi');
$element2=$('hi2');
//I need to assign element 1 and element 2 to the same hover function...
$element1.hover(function(e){
codes......
})
Thanks for any helps.
Upvotes: 1
Views: 127
Reputation: 148110
Try this,
$element1.add($element2).hover(function(e){
codes......
});
Or
$('hi, hi2').hover(function(e){
codes......
});
or If you want to do by the ids instead of hi
$('#hi, #hi2')hover(function(e){
codes......
});
Upvotes: 3
Reputation: 318182
You can use the .add() method, it constructs a new jQuery object from the union of those elements and the ones passed into the method, which means you can store the new set of elements in a variable or use it directly, like so:
var $element1=$('hi'),
$element2=$('hi2');
$element1.add($element2).hover(function(e){
codes......
});
Upvotes: 0
Reputation: 9931
So, let's say these are the elements you want to bind the hover to:
<div class="yay-for-hover">a</div>
<div class="yay-for-hover">b</div>
<div class="yay-for-hover">c</div>
You can bind with this selector in your jQuery:
$('.yay-for-hover').hover(function() {
// Do stuff here.
});
I just went with class selectors, since to me, they make the most sense here. If you want an element on your page to have the hover event triggered, just add the class to it. Check out the jQuery reference on selectors for more help.
Upvotes: 2
Reputation: 207891
If hi and hi2 were actual elements then:
$('hi,hi2').hover(...
And by actual elements I mean
$('div,p').hover(...
would work, but based on your example I can't tell what hi
and hi2
are since they're not elements, classes, IDs or something else recognizable.
Upvotes: 3