Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector: How can I select and add a class to the prev and next a tag

How can I select and add a class to the prev and next a tag.

<div class="sub">
 <ul>  
   <li><a href="#">a</a>
    <ul>
     <li><a href="#">b</a>
      <ul>
     <li><a href="#">c</a></li>
     <li><a href="#">d</a></li>
     <li><a href="#">e</a></li>
    </ul>
    </li>
     <li><a href="#">f</a></li>
     <li><a href="#">g</a></li>
   </ul>
    </li>
   <li><a href="#">h</a></li>
   <li><a href="#">i</a></li>
   <li><a href="#">j</a></li>
   </ul>
</div>

example: now i want to add 2 css classes (.prev & .next) to the the according elements presume that the mouse is over the element <li><a href="#">g</a></li>, so i want to add the 2 classes to <li><a href="#">f</a></li> and <li><a href="#">h</a></li>

snip:

$(document).ready(function() {
    $('li').css({'border-top': '1px solid green','border-bottom': '1px solid green'});

    $('li a').each(
        function(intIndex){     
            $(this).mouseover(function(){
                $(this).css({'border-top': '1px solid red','border-bottom': '1px solid red'});
                    $(this).prev().find('li').css({'border-bottom': 'none'});
                    $(this).next().find('li').css({'border-top': 'none'});
                }).mouseout(function(){
                    $(this).css({'border-top': '1px solid green','border-bottom': '1px solid green'});
            });
        }    
    );
});
like image 247
john Avatar asked Aug 04 '10 15:08

john


1 Answers

Try this: http://jsfiddle.net/rsEaF/1/

var $a = $('.sub li > a');

$a.mouseenter(function() {
    var index = $a.index(this);
    var prev = (index - 1 >= 0) ? $a.eq(index - 1).addClass('prev') : $();
    var next = $a.eq(index + 1).addClass('next');
    $a.not(prev).not(next).removeClass('prev next');
});​

EDIT: One minor correction. Previously, if you hovered over the first item, the .prev class would be added to the last item in the list. This has been corrected.


EDIT: Here's a version that uses .each() to assign the handler. Doing it this way is a little more efficient because it removes the need to call $a.index(this); for each mouseenter.

Try it out: http://jsfiddle.net/rsEaF/3/

var $a = $('.sub li > a');

$a.each(function(index) {
    $(this).mouseenter(function() {
        var prev = (index - 1 >= 0) ? $a.eq(index - 1).addClass('prev') : $();
        var next = $a.eq(index + 1).addClass('next');
        $a.not(prev).not(next).removeClass('prev next');
    });
});​

EDIT: If you're having any issue with the proper class being removed consistently, get rid of this line of code:

$a.not(prev).not(next).removeClass('prev next');

and at the beginning of the handler, replace it with:

$a.removeClass('prev next');

or:

$a.filter('.prev,.next').removeClass('prev next');
like image 162
user113716 Avatar answered Nov 15 '22 04:11

user113716