Jason Wagner
Jason Wagner

Reputation: 91

jquery toggleClass selects all list items instead of one

I'm new to jQuery and I've searched for similar issues on Stack, but haven't found this specific (and I'm sure common) issue.

I have a list of items that have a default class. I want to use toggleClass to add a rollover effect. The problem is that all of the lis are getting the toggled class instead of just the one that is being hovered.

<ul>
 <li class="my-class"><div id="my-item>1</div></li>
 <li class="my-class"><div id="my-item>2</div></li>
 <li class="my-class"><div id="my-item>3/div></li>
</ul>

$('.my-class, li').on('mouseenter', function() {
    $('#my-item').toggleClass('project-home-title-hover');
});

Upvotes: 2

Views: 241

Answers (1)

Kevin Bowersox
Kevin Bowersox

Reputation: 94469

Scope the selector with this. Also remove the comma between .my-class and li and change the selector to li.myclass. Also my-item should be a class instead of an id, ids must be unique. The markup also need some work there are unclosed end tags for one of the divs and missing quotes.

$('li.my-class').on('mouseenter  mouseleave', function() {
    $('.my-item', this).toggleClass('project-home-title-hover');
});

HTML

<ul>
 <li class="my-class"><div class="my-item">1</div></li>
 <li class="my-class"><div class="my-item">2</div></li>
 <li class="my-class"><div class="my-item">3</div></li>
</ul>

Js Fiddle: http://jsfiddle.net/SEMKr/1/

Upvotes: 3

Related Questions