Home / Articles / Programming languages / Scripting languages / JavaScript / jQuery for beginners: JavaScript menu

jQuery for beginners: JavaScript menu

jQuery for beginners: JavaScript menu
 
  • Currently 5 out of 5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Rating: 5/5 (2 votes cast)

Thank you for rating!

You have already rated this page, you can only rate it once!

Your rating has been changed, thanks for rating!

Log in or create a user account to rate this page.


In the present article I will try to focus on the implementation of JavaScript menus for your site.

If a ready code is easier for you to understand than documentation, then let's start with a page full of examples.

Slide menu

Two slide-menus on the page: top and bottom.

Example 1

Click on the link with the "top-button-menu" id, and a block with a menu will slide-down.

Present example doesn't completely explain the implementation itself, but gives JavaScript code with short explanations:

<script type="text/javascript">
  // when the page has loaded
  $( document ).ready(function(){
    // assign handler to the link with the "top-button-menu" id (top menu)
    $( '#top-button-menu' ).click(function(){
      // slide-down/hide the menu with id = top-menu
      $( '#top-menu' ).slideToggle( 'slow' );
      // change the class of the link itself
      $( this ).toggleClass( 'active' );
      // then do nothing at all (to avoid clicking the link)
      return false;
    });

    // assign handler to the link with the "bottom-button-menu" id (bottom menu)
    $( '#bottom-button-menu' ).click(function(){
      // slide-down/hide the menu with id = bottom-menu
      $( '#bottom-menu' ).slideToggle( 'slow' );
      // change the class of the link itself
      $( this ).toggleClass( 'active' );
      // then do nothing at all (to avoid clicking the link)
      return false;
    });
  });
</script>

Live demo

Slide Menu 2

Slide-menu on the left and right of the page. First, let's prepare HTML:

<div class="left">
  <!-- The content of the menu, we hide it -->
  <div class="menu">
    <ul>
      <li><a href="#" title="Item 1">Item 1</a></li>
      <li><a href="#" title="Item 2">Item 2</a></li>
      <li><a href="#" title="Item 3">Item 3</a></li>
    </ul>
    <ul>
      <li><a href="#" title="Item 1">Item 1</a></li>
      <li><a href="#" title="Item 2">Item 2</a></li>
      <li><a href="#" title="Item 3">Item 3</a></li>
    </ul>
    <ul>
      <li><a href="#" title="Item 1">Item 1</a></li>
      <li><a href="#" title="Item 2">Item 2</a></li>
      <li><a href="#" title="Item 3">Item 3</a></li>
    </ul>
  </div>
  <!-- Panel with a button -->
  <a href="#" class="button-menu"><span>&nbsp;</span>M<br>e<br>n<br>u </a>
</div>

The result should look something like this:

Example 2

 

Now let's create an event handler for links with the "button-menu" class:

// create an event handler for links with the "button-menu" class
$( '.button-menu' ).toggle(function(){
  // ... first click on the link
  // return false
  return false;
},function(){
  // ... second click on the link
  // return false
  return false;
});

Then we need to find an element with the class "menu" and push it to 120 pixels:

// go 2-levels up the DOM, inside of the element (meaning div with class left / right) we find the desired element, and we add 120 pixels to its width
$( this ).parent().parent().find( '.menu' ).animate( {width: '+=120px'}, 'slow' );
// replace the class of the button (to change the arrow)
$( this ).toggleClass( 'active' );

Connecting together:

$( document ).ready(function(){
  $( '.button-menu' ).toggle(function(){
    $( this ).parent().parent().find( '.menu' ).animate( {width: '+=120px'}, 'slow' );
    $( this ).toggleClass( 'active' ); return false;
  },function(){
    $( this ).parent().parent().find( '.menu' ).animate( {width: '-=120px', opacity: 'hide'}, 'slow' );
    $( this ).toggleClass( 'active' ); return false;
  }); 
});

Live demo

Drop-down menu

Creating horizontal drop down menus is the most common way of implementing menus for sites, and although it can be easily implemented by using CSS, the present article is about jQuery, so we'll operate within its margins. Let's start with HTML (note, for all the other examples the code is almost identical):

Example 3

And here is the actual HTML:

<div class="top-menu">
  <ul>
    <li><a href="#" title="Menu 1">Menu 1</a>
      <ul>
        <li><a href="#" title="Item 1.1">Item 1.1</a></li>
        <li><a href="#" title="Item 1.2">Item 1.2</a></li>
        <li><a href="#" title="Item 1.3">Item 1.3</a></li>
      </ul>
    </li>
    <li><a href="#" title="Menu 2">Menu 2</a>
      <ul>
        <li><a href="#" title="Item 2.1">Item 2.1</a></li>
        <li><a href="#" title="Item 2.2">Item 2.2</a></li>
        <li><a href="#" title="Item 2.3">Item 2.3</a></li>
      </ul>
    </li>
    <li><a href="#" title="Menu 3">Menu 3</a>
      <ul>
        <li><a href="#" title="Item 3.1">Item 3.1</a></li>
        <li><a href="#" title="Item 3.2">Item 3.2</a></li>
        <li><a href="#" title="Item 3.3">Item 3.3</a></li>
      </ul>
    </li>
  </ul> 
</div>

Then we need to add a handler for the event hover for the li elements:

$( '.top-menu ul li' ).hover(
  function() {
    // ...
  },
  function() {
    // ...
  }
);

Here we display the sub-menus:

// we locate the ul element and call the slideDown animation
$( this ).find( 'ul' ).slideDown();
// change the background of the selected element by adding the active class
$( this ).addClass( 'active' );

Connecting together:

$( document ).ready(function(){
  $( '.top-menu ul li' ).hover(
    function() {
      $( this ).addClass( 'active' );
      $( this ).find( 'ul' ).stop( true, true ); // stop all current animation
      $( this ).find( 'ul' ).slideDown();
    },
    function() {
      $( this ).removeClass( 'active' );
      $( this ).find( 'ul' ).slideUp( 'fast' );
    }
  );
});

Live demo

Drop-down AJAX menu

Horizontal drop down menus that download AJAX elements.

First we'll need the menu itself:

<div class="topmenu">
  <ul>
    <li id="menu1"><a href="#" title="Menu 1">Menu 1</a></li>
    <li id="menu2"><a href="#" title="Menu 2">Menu 2</a></li>
    <li id="menu3"><a href="#" title="Menu 3">Menu 3</a></li>
  </ul>
</div>

The templates for sub-menus, let's call them menu1.html, menu2.html and menu3.html - their id's are the same as the corresponding menu elements (almost for certain all the data elements will be dynamically generated, but for simplicity, use static pages):

Example 4

Example menu1.html:

<ul>
  <li><a href="#" title="Item 1">Item 1</a></li>
  <li><a href="#" title="Item 2">Item 2</a></li>
  <li><a href="#" title="Item 3">Item 3</a></li>
</ul>

Now, as in the previous example, we need an event handler hover:

$( document ).ready(function(){
  $( '.top-menu ul li' ).hover(
    function() {
      // ... here you must modify the code
      $( this ).addClass( 'active' );
    },
    function() {
      // here we leave the code as it is
      $( this ).removeClass( 'active' ); 
      $( this ).find( 'ul' ).slideUp( 'fast' );
    }
  );
});

Now we need to download the missing menu elements by using AJAX:

// we get the id of the active menu element
var id = $( this ).attr( 'id' );
// we place the active element into the local variable
var li = $( this );
$.ajax({
  // we create the name of the requested file using AJAX page
  url: 'ajax/' + id + '.html',
  beforeSend: function(){
    // before "requesting" we change the class of the element - displaying the image "loading" 
    li.addClass( 'loading' );
  },
  success: function( data ){
    // we add to the submenu data
    li.append( data );
    // show results
    li.find( 'ul' ).slideDown();
    // remove the image "loading"
    li.removeClass( 'loading' );
  }
});

Connecting together:

$( document ).ready(function(){
  $( '.top-menu ul li' ).hover(
    function() {
      // adding check - if some of the elements were loaded twice
      if( $( this ).find( 'ul' ).length == 0) {
        var id = $( this ).attr( 'id' );
        var li = $( this );
        $.ajax({
          url: 'ajax/' + id + '.html',
          beforeSend: function(){
            li.addClass( 'loading' );
          },
          success: function( data ){
            li.append( data );
            li.find( 'ul' ).stop( true, true ); // stop all current animation
            li.find( 'ul' ).slideDown();
            li.removeClass( 'loading' );
          }
        });
      } else {
        $( this ).find( 'ul' ).stop( true, true ); // stop all current animation
        $( this ).find( 'ul' ).slideDown();
      } 
      $( this ).addClass( 'active' );
    },
    function() { 
      $( this ).find( 'ul' ).slideUp( 'fast' ); 
      $( this ).removeClass( 'active' );
    }
  );
});

Live demo

Drop-down menu

Vertical drop down menu. Simple example:

Example 5
$( document ).ready(function(){
  // add an event handler hover
  $( '.top-menu ul li' ).hover(
    function() {
      $( this ).find( 'ul:first' ).stop( true, true );
      $( this ).find( 'ul:first' ).slideDown();
    },
    function() { 
      $( this ).find( 'ul:first' ).slideUp( 'fast' );
    }
  );
  // for all of the menu elements with submenus add a symbol &raquo
  $( '.top-menu li:has(ul)' ).find( 'a:first' ).append( '&raquo;' );
});

Live demo

Floating menu

Floating menu. We will need the plugin Dimensions (in order for the methods height() and width() to work) - jQuery 1.3.x no longer has a need in this plugin. Well, I think, you'll get the grasp of HTML:

Example 6

But first things first, let's start with getting some information about the current position of the "floating" menu:

// receiving information from css about the position of the top menu 
menu1 = parseInt( $( '.right' ).css( 'top' ).substring( 0, $( '.right' ).css( 'top' ).indexOf( 'px' ) ) );
// calculate the position of the bottom menu based on the size of the window (96 is approximate)
menu2 = $( window ).height() - 96;

Next step, we need to "hang" our function for the event scroll:

$( window ).scroll(function () {
  // here we drag our menus
});

And now the content:

$( window ).scroll(function () {
  // define new location for our menus
  offset1 = menu1 + $( document ).scrollTop() + 'px';
  offset2 = menu2 - $( '.left .menu' ).height() + $( document ).scrollTop() + 'px';
 
  // Drag elements to their new positions 
  $( '.right' ).animate( {top: offset1}, {duration: 500, queue: false} );
  $( '.left' ).animate( {top: offset2}, {duration: 1000, queue: false} );
});

Also add show/hide elements of the submenu:

// for all elements "a" which are inside "li" with nested lists "ul"
$( '.menu ul li:has(ul) a' ).click(function() {
  // go to parent, find "ul" and hide it
  $( this ).parent().find( 'ul' ).slideToggle(); 
  return false;
});
// "+" button - hide all "ul" nested in "li"
$( 'a.plus' ).click(function(){
  // go to parent, find the next element in DOM, in it we search for "ul li ul", execute "slideUp"
  $( this ).parent().next().find( 'ul li ul' ).slideUp( 'fast' );
  return false;
});
// "-" button - show all "ul" nested in "li"
$( 'a.minus' ).click(function(){
  // go to parent, find the next element in DOM, in it we search for "ul li ul", execute "slideDown"
  $( this ).parent().next().find( 'ul li ul' ).slideDown( 'slow' );
  return false;
});

Live demo


 

Read also

jQuery for beginners: selectors

jQuery for beginners: selectors

jQuery for beginners: AJAX

jQuery for beginners: AJAX

jQuery for JavaScript

jQuery for JavaScript

jQuery UI. Widgets. Dialog (Windows)

jQuery UI. Widgets. Dialog (Windows)

Post comment

basicuse.net
html5_css
106160485398655174790

Quick navigation

General navigation