Search code examples
javascriptjqueryjquery-uihoverjquery-hover

Not Understanding Jquery Hover


I have looked around and basically lived on the Jquery API page, but I can't seem to understand how to get a certain hover event to fire.

What I have:

<div class="profile profile-inner">
<div class="profile-footer">
<ul class="profile-actions">

What I want:

The ul class is hidden. Then once the div class "profile profile-inner" is hovered I want the ul class to be visible.

Notes:

As far as I know, I will have to use this because there are many div classes profile profile-inner (because of many different members' profiles on that particular page)


Solution

  • .hover() takes two arguments: a function to call when transitioning to the "hover state", and another function to call when leaving the "hover state":

    $('.profile.profile-inner').find('ul').hide();
    $('.profile.profile-inner').hover(function() {
      $(this).find('ul').show();
    }, function() {
      $(this).find('ul').hide();
    });
    

    I don't recommend doing this: Depending on the layout of your page, detecting hover with Javascript may be unreliable, and you may get "stuck" in a state. This can annoy users, and fortunately, you can use CSS by itself to do what you want:

    .profile.profile-inner ul { display: none; }
    .profile.profile-inner:hover ul { display: block; }
    

    If your outer element is an <a> tag, this will even work in MSIE6.

    If you want further backwards-compatibility, I recommend creating a behavior-shim to complement the CSS-based method instead of using jQuery's hover. This method works all the way back to MSIE4.