Query for beginners: Java Script menu

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:

  // 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;
    });
  });

Live demo

Slide Menu 2

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

M
e
n
u

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:

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:

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:

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 »
  $('.top-menu li:has(ul)').find('a:first').append('»');
});

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;
});

Continue reading here: Query for beginners: AJAX

Was this article helpful?

0 0