Kim
Kim

Reputation: 1156

addClass to closest span with class

I'm trying to add a Class on mouseover on the element "goto" and give class "active" to the arrow with class "arrow", how is this done?

  $('.goto').on('mouseover',function() {
 $('.goto').find('.arrow').addClass('active')  
 })

<span class="goto">Hover here<span class="arrow"><img src="assets/img/arrow.png">    </span></span>
<span class="goto">Hover here<span class="arrow"><img src="assets/img/arrow.png"></span></span>

Upvotes: 1

Views: 853

Answers (3)

user1823761
user1823761

Reputation:

Working jsFiddle Demo

Use this:

$(function () {
    $('.goto').on('mouseover',function() {
        $(this).find('.arrow').addClass('active');
    });
});

Also you can attach mouseout to put it back:

$(function () {
    $('.goto')
        .on('mouseover',function() {
            $(this).find('.arrow').addClass('active');
        })
        .on('mouseout',function() {
            $(this).find('.arrow').removeClass('active');
        });
});


TIP

You can do this with CSS only, in this situation, there is no need to use jQuery:

.goto:hover .arrow {
    /* rules for make it active */
}

Upvotes: 2

Ford
Ford

Reputation: 2597

$('.goto .arrow').on('mouseenter', function() {
    $(this).addClass('active');
}).on('mouseleave', function() {
    $(this).removeClass('active');
});

Upvotes: 0

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

Your code is actually searching for every .goto when you hover one. Use this :

$(this).find('.arrow').addClass('active')

this is the reference of the hovered .goto.

Upvotes: 0

Related Questions