Danny Englander
Danny Englander

Reputation: 2044

jQuery show / hide panel and then hover over content within a panel

I've got an item list where I want to show a related panel if the item list item is hovered over. I've got it working but the issue is that I cannot then hover over content within the panel once I've hovered over the linked list item for obvious reasons as I use a mouseleave function.

I've been at this for a few days and cannot work out the logic of what needs to be done to leave the related panel open so I can hover over it and click a read more link within it.

I tried adding a class on the hover state to the panel but that did not seem to work either.

My HTML is:

<div id="item-wrapper">
    <ul>
        <li><a href="#" id="item-1">Item 1</a>
        </li>
        <li><a href="#" id="item-2">Item 2</a>
        </li>
    </ul>
</div>

<div id="panel-1" class="panel">
     <h2>This is panel 1!</h2>
    <a href="#">read more 1...</a>
</div>

<div id="panel-2" class="panel">
     <h2>This is panel 2!</h2>
    <a href="#">read more 2...</a>
</div>

My basic jQuery is:

$('#item-1').mouseenter(function () {
    $('#panel-1.panel').toggle();
});

$('#item-1').mouseleave(function () {
    $('#panel-1.panel').toggle();
});

$('#item-2').mouseenter(function () {
    $('#panel-2.panel').toggle();
});

$('#item-2').mouseleave(function () {
    $('#panel-2.panel').toggle();
});

... and then I have some CSS where the panels are set to display: none to begin with. Note, if neither list item links are hovered then the panels should go away if one had been open previous to that.

Fiddle demo here...

Upvotes: 0

Views: 5022

Answers (2)

Tyler Rash
Tyler Rash

Reputation: 1173

A couple things:

  1. User a hover event handler on the li, not the a.
  2. This allows you to move your content into the lis, so that hovering on the content means you're still hovering over its parent, the li.

jQuery:

$('#item-1').parent().hover(function () {
    $('#panel-1.panel').toggle();
});

$('#item-2').parent().hover(function () {
    $('#panel-2.panel').toggle();
});

Forked jsFiddle

Upvotes: 1

Neil S
Neil S

Reputation: 2304

In my opinion, the only real way to approach this is to wrap the hidden elements in the element that you are hovering, so that the mouseleave event can be tied to the wrapper.

LINK UPDATED: here's a fiddle

I also used data attributes on the elements to track which panel to open. This way, you only need the following code:

$('#item-wrapper a').mouseenter(function (e) {
    if ($(this).data('panel')) {
        $('.panel').hide();
        $('#' + $(this).data('panel')).show();
    }
});
$('#item-wrapper').mouseleave(function () {
    $('.panel').hide();
});

EDIT: added a conditional to make sure anchor tags in the panels don't trigger the hover event.

Upvotes: 1

Related Questions