0

I am new to jQuery and i want to figure out how to select multiple elements for my navigation bar i'm trying to create. I want to have it check if the users mouse is over the item in the navigation bar or over the drop down menu (otherwise the drop down menu would disappear). I have tried to use: $('#nav_item_1').mouseenter(function(){
//make the drop down menu visible and change nav_item background here
});
`

$('#nav_item_1,#dropdown').mouseleave({
    //revert everything back to normal
});

but then when i try to move my mouse from the item in the navigation bar to the drop down menu it reverts everything back to normal.

Alec B
  • 1

2 Answers2

0

The issue that you're having is because when you leave the navigation bar item .mouseleave is being triggered instantly hiding the #dropdown with it.

What I would do here is set a slight time out on the mouseleave event of the nav_item about half a second or less to hide the dropdown. This will allow the user the amount of seconds set outside of the navigation bar so that they can hover over the dropdown. After the user is on the #dropdown I would clear the timeout preventing the normal behavior of the dropdown hiding.

How would you do this with code?
$('#nav_item_1').mouseleave(function() {
/* set your time out here to return everything to normal. Because we want to allow the dropdown to stay visible for a fraction of time required to move the cursor to the dropdown.*/
});

And then,
$('#dropdown').mouseenter(function() {
// clear the timer to prevent normal behavior (keeping the dropdown visible).
});

Check out this link: http://www.w3schools.com/js/js_timing.asp

Regarding your original question about selecting multiple items. You are doing it corrently. But as I explained above your code is not reaching the mouseleave event of the #dropdown.

user1027620
  • 2,745
  • 5
  • 37
  • 65
0

The second piece of code makes it so that when you leave #nav_item_1 OR #dropdown, everything will be reverted. So when you leave the #nav_item_1 to go to the #dropdown, the event will fire.

You could check every mouse move if the current mouse target contains the dropdown or nav_item:

$("#nav_item_1").mouseenter(function () {
  // make menu visible etc
}

$(document).mousemove(function (e) { // note the e parameter
  if ($(e.target).has("#dropdown,#nav_item_1").length !== 0) {
    // revert
  }
}

This requires the two elements to be very close to each other in order for it to work properly though.

ChrisF
  • 857
  • 9
  • 9