JQuery, how to apply the same mouseover effect to multiple divs with the same classes? help please?

6.4k views Asked by At

i am new to jQuery and i am having some rollover issues, i am trying to apply the same "roll over" effect to multiple divs, and it seems to work, the only thing is when i roll over an element all of my divs get the same effect, when i would like them to apply the effect one at a time on mouse over, here is my code

  $('div.pitem').bind('mouseenter mouseleave', function() {
  $('div.p-tab').toggleClass('pheader-bar-selected');
  });
  $('div.pitem').bind('mouseenter mouseleave', function() {
  $('div.p-fline').toggleClass('pfooter-bar-selected');
  });

I do realize that i have the same classes on all of my divs but i was hoping to find a way to do this with out giving every single div a unique class or id, any help would be amazing thank you!

2

There are 2 answers

4
s_hewitt On BEST ANSWER

What you are doing currently is on every hover you toggle the CSS class on all elements selected by div.p-tab, which will be any DIV with the CSS class p-tab.

What you want to do is only toggle the CSS class on elements next to the hovered element in your HTML structure div.pitem.

To find the currently hovered item, in your event use this keyword, and turn it into a jQuery object by using $(this). To find elements next to (adjacent) you will use the siblings function. You can also combine your two hover events.

$('div.pitem').bind('mouseenter mouseleave', function() { 
    $(this).siblings('div.p-tab').toggleClass('pheader-bar-selected');
    $(this).siblings('div.p-fline').toggleClass('pfooter-bar-selected');
}); 


<div class="grid_3 portfolio-item">
    <div class="p-tab pheader-bar">
        <span class="tfm-drpa">&raquo;</span>
    </div>
    <div class="pitem">
        <a href="#"></a>
    </div>
    <h2 class="pcontent">Consectetuer Adipiscing Elit<span class="ptitlelines">///</span></h2>
    <div class="p-fline pfooter-bar"></div> 
</div>
1
cfEngineers On

You might take a look at $(this).

Explained at: http://remysharp.com/2007/04/12/jquerys-this-demystified/

Here is how I use it to give you an example

// megalink hover
$("div.megalink").hover(function(){
    $(this).css('background','#e1eefd');
    $(this).css('border-bottom','1px solid #0470B8');
 }, function(){
    $(this).css('background','#ffffff');
    $(this).css('border-bottom','1px solid #EBE7DE');
});