user979331
user979331

Reputation: 11851

jQuery toggle between two classes inside this

I have this line of code:

$(".dropdown").hover(function () {
        $(".down, .up").toggleClass("down up");
    });

And this works, but I want it to toggle between the two classes inside this dropdown element, currently it toggles between two classes for all .dropdown elements.

I know you can do this $(".down", this).... but how would I apply that to both .down and .up?

Upvotes: 0

Views: 855

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can achieve this by simply adding the this context to the selector you're already using, for example:

$(".dropdown").hover(function () {
  $(".down, .up", this).toggleClass("down up");
});

However I'd suggest that using CSS would be a much better alternative. It's more semantic, and also performs much better:

.dropdown .down { color: red; }
.dropdown .up { color: blue; }

.dropdown:hover .down { color: blue; }
.dropdown:hover .up { color: red; }
<div class="dropdown">
  <div class="up">Up</div>
  <div class="down">Down</div>
</div><br />

<div class="dropdown">
  <div class="up">Up</div>
  <div class="down">Down</div>
</div>

Upvotes: 3

user1400290
user1400290

Reputation: 1750

Or it could be:

$(".dropdown").hover(function () {
    $(this).find(".down, .up").toggleClass("down up");
});

Upvotes: 4

Related Questions