Implement this

Asked

Viewed 84 times

5

There are several Ivs with the class .categorias and I need to display the element .nav-a only in the div category that I have the mouse on top of it at the moment.

What is currently happening is that when I hover over any of the Divs .categorias he displays the .nav-a in all of them, and not only in .categorias in question.

Follow the current code for reference.

$(document).ready(function(){
    $('.nav-a').hide();

    $('.categorias').mouseenter(function(){
         $('.nav-a').fadeIn();
    });

    $('.categorias').mouseleave(function(){
         $('.nav-a').fadeOut();
    });
});
  • 3

    If . Nav-a is the child of . categories, do this $(this). find('.Nav-a'). fadein(); or $(this + '.Nav-a'). fadein() and tell me if it worked, it would be interesting to post your HTML

  • 2

    Also post HTML, so we understand how your DOM is.

  • 1

    @Diegovieira Regardless of HTML, your first suggestion seems correct. Post this as an answer!

  • By the way, I’m assuming that the excitement of showing and hiding is important to you, right? Otherwise, a solution simply with CSS would suffice (and if the target are modern browsers, even the case of animation - using CSS3 transitions)

  • Thank you, Diego Vieira’s solution solved my problem.

  • 1

    Just a hint: if you will be using the same selector directly, and if the amount of items obtained will not change, transforms the $(".nav-a") in a variable. Type var foo = $(".nav-a");. This will make your life easier ;)

Show 1 more comment

2 answers

7


Use in this way

Jquery

$(document).ready(function(){
    $('.nav-a').hide();

    $('.categorias').mouseenter(function(){
         $(this).find('.nav-a').fadeIn();
    });

    $('.categorias').mouseleave(function(){
         $(this).find('.nav-a').fadeOut();
    });
});

Another way to do and "minimize code"

$(document).ready(function(){  
   $('.categorias')
     .mouseenter(function(){
         $(this).find('.nav-a').fadeIn();
    })
     .mouseleave(function(){
          $(this).find('.nav-a').fadeOut();
    });
});

Very well observed by our friend @Ronnyamarante remove this from your code: $('.nav-a').hide(); and do what in your CSS.

CSS

.nav-a {
   display: none;
}
  • Perfect, thank you very much.

5

Just to complement the correct @Diegovieira response, you can also group these events as follows:

Tip: $('.nav-a').hide(), use your CSS for this.

$( '.categorias' ).on({
     mouseenter: function() {
    $(this).find('.nav-a').fadeIn();
  }, mouseleave: function() {
    $(this).find('.nav-a').fadeOut();
  }
});
  • 1

    I would put more options now, think it necessary I reedit my answer?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.