pobliska
pobliska

Reputation: 247

jQuery hover in function

My script works fine without $this, but when I delete $this, then on hover script display all submenus. Could someone explain me where I make mistake?

$(function () {
    var timeoutId;
    $(".mainmenu li").hover(function () {
            if (!timeoutId) {
                timeoutId = window.setTimeout(function () {
                    timeoutId = null;
                    $(this).find('.submenu').slideDown('slow');
                }, 1500);
            }
        },
        function () {
            if (timeoutId) {
                window.clearTimeout(timeoutId);
                timeoutId = null;
            } else {
                $(".submenu").slideUp('slow');
            }
        });
});

My html:

<div id="a">
   <ul class="mainmenu">
   <li>
      CARS
      <ul class="submenu">
         <li><a href="#">White</a></li>
         <li><a href="#">Black</a></li>
         <li><a href="#">Red</a></li>
         <li><a href="#">Silver</a></li>
         <li><a href="#">Yellow</a></li>
         <li><a href="#">Other</a></li>
      </ul>
   </li>
   <li>
      TIRES
      <ul class="submenu">
         <li><a href="#">14"</a></li>
         <li><a href="#">15"</a></li>
         <li><a href="#">16"</a></li>
         <li><a href="#">17"</a></li>
         <li><a href="#">18"</a></li>
      </ul>
   </li>
</div>

.mainmenu has more than 2 submenus.

Upvotes: 1

Views: 71

Answers (1)

J&#246;rn
J&#246;rn

Reputation: 845

it's just an untested shot in the dark, but i think you're loosing the element context in your hover function by using the context of the timeout function.
use something like a self variable to store the element and use it after the timeout expired.

$(function () {
    var timeoutId;
    $(".mainmenu li").hover(function () {
            // store the context
            var self = this;

            if (!timeoutId) {
                timeoutId = window.setTimeout(function () {
                    timeoutId = null;
                    // this represents the context of the timeout function
                    // we're using the stored context here
                    $(self).find('.submenu').slideDown('slow');
                }, 1500);
            }
        },
        function () {
            if (timeoutId) {
                window.clearTimeout(timeoutId);
                timeoutId = null;
            } else {
                $(".submenu").slideUp('slow');
            }
        });
});

Upvotes: 2

Related Questions