Klausos Klausos Klausos Klausos - 10 months ago 27
HTML Question

Jquery navigation menu

The above code does not work properly. I need to implement a simple menu with sub-menu items using Jquery. When I open the web-page, I see the content of all menus and submenus all together (like a stack). I need to improve JavaScript shown below in order to properly assign the content to menu items. So, when I click "menu2",there should be the content of DIV id = "menu2". Now I see all content on one page.

<!-- Start css3menu.com BODY section -->
<ul id="css3menu1">
<li class="topfirst"><a class="pressed" href="#menu1" style="height:40px;line-height:40px;"><span>menu1</span></a>
<ul class = "menu">
<li><a href="#submenu11">submenu11</a></li>
<li><a href="#submenu12">submenu12</a></li>
<li><a href="#submenu13">submenu13</a></li>
<li><a href="#submenu14">submenu14</a></li>
<li class="menu"><a href="#menu2" style="height:40px;line-height:40px;">menu2</a></li>
<li class="menu"><a href="#menu3" style="height:40px;line-height:40px;">menu3</a></li>
<li class="toplast"><a href="#menu4" style="height:40px;line-height:40px;">menu4</a></li>
<!-- End css3menu.com BODY section -->

$('ul.menu').each(function() {
var $active, $content, $links = $(this).find('a');
$active = $links.first().addClass('active');
$content = $($active.attr('href'));
$links.not(':first').each(function() {

$(this).on('click', 'a', function(e) {
$active = $(this);
$content = $($(this).attr('href'));


This line has an issue

$content = $($active.attr('href'));

There is no item with that ID... ($content is length 0)


  1. you press a link with href="#menu1"
  2. $active.attr('href') equals to #menu1
  3. which translates to $content = $("#menu1");
  4. there is no element on the page with ID "menu1"

In jQuery a selector with a hash (#) means - find an element with the id after the hash sign

So #menu1 means the same (almost) as document.getElementById("menu1")

However there is no element with that ID (or any id that is equal to the href values)

It might not be the last issue, but this is the next stop in the attempt to make it work...

See in jsFiddle