简体   繁体   中英

Adding a active class to all span within a div

I have a div with 2 span as a link, I want to add active class on both span when mouse enters the container div ie fos-search-items

var $hover_element = $('.fos-search-items');
    .mouseenter(function() {
        $(this).find("span").addClass('fos-db-active');
    })
    .mouseleave(function() {
        $(this).find("span").removeClass('fos-db-active');
    })

Try this

var $hover_element = $('.fos-search-items');
 $hover_element.mouseenter(function() {
  $( this ).find( "span" ).addClass('fos-db-active');
  })

 $hover_element.mouseleave(function() {
  $( this ).find( "span" ).removeClass('fos-db-active');

  })

Working demo

You have not attached the events correctly. mouseenter and mouseleave should be attached to DOM elements jquery object.Like this:

$('.fos-search-items').mouseenter(function() {
    $(this).find("span").addClass('fos-db-active');
})
$('.fos-search-items').mouseleave(function() {
    $(this).find("span").removeClass('fos-db-active');
})

also, you can rather use .hover() with two function argumenents for mousenter and mouseleave:

$('.fos-search-items').hover(function(){
   $(this).find('span').addClass('fos-db-active')
},function(){
   $(this).find('span').removeClass('fos-db-active')
});

You should use $hover_element on event while mouseenter and mouseleave

Option 1 Demo Here

var $hover_element = $('.fos-search-items');

$hover_element.mouseenter(function() {
    $(this).find("span").addClass('fos-db-active');
});

$hover_element.mouseleave(function() {
    $(this).find("span").removeClass('fos-db-active');
});

Option 2 Demo Here

Just remove the ; after the $('.fos-search-items')

var $hover_element = $('.fos-search-items').mouseenter(function() {
        $(this).find("span").addClass('fos-db-active');
    }).mouseleave(function() {
        $(this).find("span").removeClass('fos-db-active');
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM