Reputation: 11
I have a menu hortizontal, with horizontal sub and subsub menu. On click the sub menu should appear and stay visible. If I go to a page from the submenu, the sub sub menu should be visible. I searched this site and the web for answers.
UPDATE
I'v modified the script, thanks to the answers you gave, that put me in the right direction and found a example here on stackoverflow. The click is for tablets eo, for screens I like a hover. I tried to combine the script with a hover function, works.
$('#menu li').hover(function() {
$(this).find('ul').show();
},
function() {
$(this).find('ul').hide();
});
Tried to combine the hover and click like this, but then the hover is not working. What am I doing wrong?
$(document).ready(function(){
$('.sub').hide();
$('#menu li a').on('click hover ', function(event){
if ($(this).next('ul.sub').children().length !== 0) {
event.preventDefault();
}
$(this).siblings('.sub').slideToggle('slow');
});
});
css
.sub{display:none;}
HTML
<ul id="menu">
<li><a href="item.php">Item</a></li>
<li><a href="item1.php">item1</a>
<ul class="sub">
<li><a href="subitem1">subitem1</li>
<ul class="subsub">
<li> <a href="subsub1.php">subsub1</a></li>
<li> <a href="subsub2.php">subsub2</a></li>
<li> <a href="subsub3.php">subsub3</a></li>
</ul></li>
<li><a href="subitem2.php">subitem2</a></li>
</ul></li>
</ul>
Jquery
//Hide all the sub menus
$('.sub').hide();
$('#menu li a').click(function(event){
if ($(this).next('ul.sub').children().length !== 0) {
}
$(this).siblings('.sub').slideToggle('slow');
});
});
Upvotes: 0
Views: 2454
Reputation: 1794
Lets say that you want to access the submenu for item1.php. the jQuery will look something like this
$(function() {
$('a', '#menu').click(function(e) {
e.preventDefault();
$(this).parent().find('.sub').show();
});
});
Here is my jsFiddle
UPDATE 1: Mentioned in the comments below, user can not navigate actual links inside the menu. to fix this, add a class (I will use pageChange) to the links you want to to allow to change pages in the browser. to achieve this take my above code and bind it to your specified class. You will also need to add the class to the link tags too.
$(function() {
$('a', '#menu').click(function(e) {
if ($(this).hasClass('pageChange') === true) {
return;
}
e.preventDefault();
$(this).parent().find('.sub').show();
});
});
Here is a new jsFiddle for above code: http://jsfiddle.net/pSKYk/3/
Upvotes: 1
Reputation: 1984
Your immediate issue is setting a link to the menu options that show the submenus. When they're clicked, it will attempt to take you out of the page.
Here's a jsfiddle with it working (to my understanding). I also added toggle functionality, so it will hide the menu when clicked again: http://jsfiddle.net/9gcnm/1/
$(function() {
});
is jQuery shorthand for
$(document).ready(function(){
});
Upvotes: 0