Jquery - Non-nested / Non-descendant Sibling Navigation Shown On Hover Event
Solution 1:
You're part of the way there @EpF. The problem is that your semantic example given above (which is possible to adhere to) is trying to capture a mouseleave
event and while it's possible to use jQuery's .not() function to achieve this, it would be expensive. Really, the smartest way to do this is to have an outer wrapper for your whole navigation (wrapping all div's you've got in your existing fiddle) and then bind your show()
event to mouseenter
, while separately binding your .hide()
event (the one for ALL .subz
) to an event triggered on mouseleave
for the wrapper div.
Given the following HTML:
<divid="nav-wrap"><ulclass="mainz"><liclass="1">item 1</li><liclass="2">item 2</li></ul><divclass="subz"><ulclass="1"><li>1 sub item 1</li><li>1 sub item 2</li></ul><ulclass="2"><li>2 sub item 1</li><li>2 sub item 2</li></ul></div></div><!-- /END #nav-wrap -->
You can achieve the effect with the following javascript
$( document ).ready( function () {
var $ul = $( '.subz ul' ).hide();
$( '.mainz li' ).on( 'mouseenter', function(event){
$ul.hide().eq( $( this ).index() ).show();
});
$( '#nav-wrap' ).on( 'mouseleave', function(event){
$ul.hide();
});
});
Here is a JSFiddle of it in action: http://jsfiddle.net/XY4mH/4/
Also, I should note that the .hover()
function is deprecated in jQuery for quite a while now and could disappear sometime soon. Note that I used the .on()
function, which is the correct way to bind these kinds of events in jQuery.
Solution 2:
$( document ).ready( function () {
$( '.main li' ).on( 'click', function () {
$( '.sub ul' )
.hide()
.eq( $( this ).index() )
.show();
});
});
That should do the trick. But as @Mottie said, nesting menus would work better / more symantecly
Edit: Sorry this is working on click
. Just a sec and I'll have it updated
$( document ).ready( function () {
var $ul = $( '.sub ul' ).hide();
$( '.main li' ).hover(
function () {
$ul
.hide()
.eq( $( this ).index() )
.show();
},
function () {
$ul.hide()
}
);
});
Post a Comment for "Jquery - Non-nested / Non-descendant Sibling Navigation Shown On Hover Event"