Chro
Chro

Reputation: 1003

Select only hovered elements instead of all matching elements

My HTML is of the form:

<ul>
    <li class="tile">
        <span class="hidden"></span>
        <span class="hidden"></span>
    </li>
    <li class="tile">
        <span class="hidden"></span>
        <span class="hidden"></span>
    </li>
</ul>

And when an li with class tile is hovered on I need the first span with class hidden to have that class removed. When the mouse is moved away that span needs to be hidden again. So far I have this:

$(".tile").hover(function () {
    $(this + ":first-child").removeClass("hidden");
}, function () {
    $(this + ":first-child").addClass("hidden");
});

However this makes ALL of the li with class tile do the action, not just the one hovered upon. And the second function gives the hidden class to the style sheet reference in the header!

What am I doing wrong? I thought I used this correctly.

Upvotes: 0

Views: 85

Answers (2)

Strelok
Strelok

Reputation: 51441

Your hover function should be:

$(".tile").hover(function () {
    $(this).find("span").first().removeClass("hidden");
}, function () {
    $(this).find("span").first().addClass("hidden");
});

Upvotes: 1

BoltClock
BoltClock

Reputation: 723528

Don't try to concatenate this with other selectors, as it doesn't do what you think it does.

Use .find() instead:

$(".tile").hover(function () {
    $(this).find(":first-child").removeClass("hidden");
}, function () {
    $(this).find(":first-child").addClass("hidden");
});

Upvotes: 2

Related Questions