Switch Menu Using JQuery

Introduction

In this article I'm going to make a simple Switch Menu using jQuery. Switch Menu is a common UI component in many applications. A number of JavaScript libraries provide nice and simple Switch Menus, but today we are going to take a look at how to build our own - because, well, that is what we do here at Switch On The Code!

Switch Menu

Switch Menu now supports persistence (so it remembers which menu item was last expanded) whenever you revisit the page. To sweeten the deal, you can choose between "sitewide" and "local" persistence, with the former remembering the menu state across your entire site. This is useful if you have the exact same Switch Menu script on multiple pages on your site (as a navigational bar), and it makes sense for the persistence to last from page to page. Now it's time to see how we will make it.

Step 1: First we have to create a web Application.

  • Go to Visual Studio 2010.
  • New--> And select the web Application.
  • Give it's a name whatever you want.
  • Click OK.

img1.gif

Step 2: Secondly you have to add a new page to the website.

  • Go to the Solution Explorer.
  • Right Click on the Project name.
  • Select add new item.
  • Add new web page and give it a name.
  • Click OK.

img2.gif

img3.gif

Step 3: In this step you add some images to the project; let us see what it will look like. These are the images that I used but you can use your own images, whatever you want to do.

img4.gif

Step 4: In this code you will see that we have to add some images inside the default2.aspx page; now let us see how we will add it. First of all we have to take a div and inside it we will take the images; whatever the number you want, let us see the body code of the default2.aspx page.

Body Code

<body>
    <form id="form1" runat="server">
    <div id="masterdiv">
<div class="menutitle" onclick="SwitchMenu('sub1')">Technologies</div>
<span class="submenu" id="sub1">
- <a href="http://www.c-sharpcorner.com/1/237/net-4-0.aspx">.NET 4.0</a><br>
- <a href="http://www.c-sharpcorner.com/1/233/asp-javascript-css.aspx">Web Development</a><br>
- <a href="http://www.c-sharpcorner.com/1/236/jquery.aspx">JQuery</a><br>
- <a href="http://www.c-sharpcorner.com/1/176/ajax.aspx/">AJAX Zone</a>
</span>
<
div class="menutitle" onclick="SwitchMenu('sub2')"> Resources</div>
<span class="submenu" id="sub2" style="background-color: #FFFFFF">
- <a href="www.c-sharpcorner.com/Authors/">Author</a><br>
- <a href="http://www.c-sharpcorner.com/Prizes/">Prizes</a><br>
- <a href="http://www.c-sharpcorner.com/Tips/">Tips</a>
</span>
<
div class="menutitle" onclick="SwitchMenu('sub3')">Help Forum</div>
<span class="submenu" id="sub3">
- <a href="http://www.codingforums.com">Coding Forums</a><br>
</span> 
<div class="menutitle" onclick="SwitchMenu('sub4')">Cool Links</div>
<span class="submenu" id="sub4">
- <a href="http://www.javascriptkit.com">JavaScript Kit</a><br>
- <a href="http://www.mindcracker.com/">MindCracker</a><br>
- <a href="http://www.cooltext.com">Cool Text</a><br>
- <a href="http://www.google.com">Google.com</a>
</span> 
<img  src="Image/start.gif"  onclick="SwitchMenu('sub5')"><br>
<span class="submenu" id="sub5">
- <a href="http://www.c-sharpcorner.com/">Link to Us</a><br>
- <a href="http://www.c-sharpcorner.com/Resources/AboutUs.aspx">Know Us</a><br>
- <a href="http://www.c-sharpcorner.com/">Email Us</a><br>
</span>
</
div>
    </form>
</body>

Step 5: In this step we will see how to add a style sheet code. Whenever we write the style sheet code we have be careful that it will be written inside the <style></style> tags and you have to place it inside the head section.

Style Code:

<style type="text/css">
        .menutitle
        {
            cursor: pointer;
            margin-bottom: 5px;
            background-color: #5D478B;
            color: #87CEEB;
            width: 180px;
            padding: 2.5px;
            text-align: center;
            font-weight: bold;
/*/*/
            border: 2px solid #FF0000; /* */
        }
       
.submenu
        {
            margin-bottom: 0.5em;
        }
</
style
>

 Step 6: In this step we have to write the script reference to the aspx page; let us see from where you have to write the script code.

img5.gif

Step 7: Let us see the script code which you have to add inside the <script></script> tags and that will be paced either in the head section or the body section as you want.

<script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script>

Step 8: In this step we have to write the jQuery code which is given below.

<script type="text/javascript">
        var persistmenu = "yes" //"yes" or "no". Make sure each SPAN content contains an incrementing ID starting at 1 (id="sub1", id="sub2", etc)
        var persisttype = "sitewide" //enter "sitewide" for menu to persist across site, "local" for this page only
        if (document.getElementById) { //DynamicDrive.com change
            document.write('<style type="text/css">\n')
            document.write('.submenu{display: none;}\n')
            document.write('</style>\n')
        }
        function SwitchMenu(obj) {
            if (document.getElementById) {
                var el = document.getElementById(obj);
                var ar = document.getElementById("masterdiv").getElementsByTagName("span"); //DynamicDrive.com change
                if (el.style.display != "block") { //DynamicDrive.com change
                    for (var i = 0; i < ar.length; i++) {
                        if (ar[i].className == "submenu") //DynamicDrive.com change
                            ar[i].style.display = "none";
                    }
                    el.style.display = "block";
                } else {
                    el.style.display = "none";
                }
           }
        }
       function get_cookie(Name) {
            var search = Name + "="
            var returnvalue = "";
            if (document.cookie.length > 0) {
                offset = document.cookie.indexOf(search)
                if (offset != -1) {
                    offset += search.length
                    end = document.cookie.indexOf(";", offset);
                    if (end == -1) end = document.cookie.length;
                    returnvalue = unescape(document.cookie.substring(offset, end))
                }
            }
            return returnvalue;
        }
        function onloadfunction() {
            if (persistmenu == "yes") {
                var cookiename = (persisttype == "sitewide") ? "switchmenu" : window.location.pathname
                var cookievalue = get_cookie(cookiename)
                if (cookievalue != "")
                    document.getElementById(cookievalue).style.display = "block"
            }
        }
        function savemenustate() {
            var inc = 1, blockid = ""
            while (document.getElementById("sub" + inc)) {
                if (document.getElementById("sub" + inc).style.display == "block") {
                    blockid = "sub" + inc
                    break
                }
                inc++
            }
            var cookiename = (persisttype == "sitewide") ? "switchmenu" : window.location.pathname
            var cookievalue = (persisttype == "sitewide") ? blockid + ";path=/" : blockid
            document.cookie = cookiename + "=" + cookievalue
        }
        if (window.addEventListener)
            window.addEventListener("load", onloadfunction, false)
        else if (window.attachEvent)
            window.attachEvent("onload", onloadfunction)
        else if (document.getElementById)
            window.onload = onloadfunction
        if (persistmenu == "yes" && document.getElementById)
            window.onunload = savemenustate
</script
>

Step 9: In this step we will see the complete code for the Default2.aswpx page; let us see the code given below.

Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js"></script
>
<script type="text/javascript">
        var persistmenu = "yes" //"yes" or "no". Make sure each SPAN content contains an incrementing ID starting at 1 (id="sub1", id="sub2", etc)
        var persisttype = "sitewide" //enter "sitewide" for menu to persist across site, "local" for this page only
        if (document.getElementById) { //DynamicDrive.com change
            document.write('<style type="text/css">\n')
            document.write('.submenu{display: none;}\n')
            document.write('</style>\n')
        }
        function SwitchMenu(obj) {
            if (document.getElementById) {
                var el = document.getElementById(obj);
                var ar = document.getElementById("masterdiv").getElementsByTagName("span"); //DynamicDrive.com change
                if (el.style.display != "block") { //DynamicDrive.com change
                    for (var i = 0; i < ar.length; i++) {
                        if (ar[i].className == "submenu") //DynamicDrive.com change
                            ar[i].style.display = "none";
                    }
                    el.style.display = "block";
                } else {
                    el.style.display = "none";
                }
           }
        }
       function get_cookie(Name) {
            var search = Name + "="
            var returnvalue = "";
            if (document.cookie.length > 0) {
                offset = document.cookie.indexOf(search)
                if (offset != -1) {
                    offset += search.length
                    end = document.cookie.indexOf(";", offset);
                    if (end == -1) end = document.cookie.length;
                    returnvalue = unescape(document.cookie.substring(offset, end))
                }
            }
            return returnvalue;
        }
        function onloadfunction() {
            if (persistmenu == "yes") {
                var cookiename = (persisttype == "sitewide") ? "switchmenu" : window.location.pathname
                var cookievalue = get_cookie(cookiename)
                if (cookievalue != "")
                    document.getElementById(cookievalue).style.display = "block"
            }
        }
        function savemenustate() {
            var inc = 1, blockid = ""
            while (document.getElementById("sub" + inc)) {
                if (document.getElementById("sub" + inc).style.display == "block") {
                    blockid = "sub" + inc
                    break
                }
                inc++
            }
            var cookiename = (persisttype == "sitewide") ? "switchmenu" : window.location.pathname
            var cookievalue = (persisttype == "sitewide") ? blockid + ";path=/" : blockid
            document.cookie = cookiename + "=" + cookievalue
        }
        if (window.addEventListener)
            window.addEventListener("load", onloadfunction, false)
        else if (window.attachEvent)
            window.attachEvent("onload", onloadfunction)
        else if (document.getElementById)
            window.onload = onloadfunction
        if (persistmenu == "yes" && document.getElementById)
            window.onunload = savemenustate
</script
>
<style type="text/css">
        .menutitle
        {
            cursor: pointer;
            margin-bottom: 5px;
            background-color: #5D478B;
            color: #87CEEB;
            width: 180px;
            padding: 2.5px;
            text-align: center;
            font-weight: bold;
/*/*/
            border: 2px solid #FF0000; /* */
        }
       
.submenu
        {
            margin-bottom: 0.5em;
        }
</
style
>
<body>
    <form id="form1" runat="server">
    <div id="masterdiv">
<div class="menutitle" onclick="SwitchMenu('sub1')">Technologies</div>
<span class="submenu" id="sub1">
- <a href="http://www.c-sharpcorner.com/1/237/net-4-0.aspx">.NET 4.0</a><br>
- <a href="http://www.c-sharpcorner.com/1/233/asp-javascript-css.aspx">Web Development</a><br>
- <a href="http://www.c-sharpcorner.com/1/236/jquery.aspx">JQuery</a><br>
- <a href="http://www.c-sharpcorner.com/1/176/ajax.aspx/">AJAX Zone</a>
</span>
<
div class="menutitle" onclick="SwitchMenu('sub2')"> Resources</div>
<span class="submenu" id="sub2" style="background-color: #FFFFFF">
- <a href="www.c-sharpcorner.com/Authors/">Author</a><br>
- <a href="http://www.c-sharpcorner.com/Prizes/">Prizes</a><br>
- <a href="http://www.c-sharpcorner.com/Tips/">Tips</a>
</span>
<
div class="menutitle" onclick="SwitchMenu('sub3')">Help Forum</div>
<span class="submenu" id="sub3">
- <a href="http://www.codingforums.com">Coding Forums</a><br>
</span> 
<div class="menutitle" onclick="SwitchMenu('sub4')">Cool Links</div>
<span class="submenu" id="sub4">
- <a href="http://www.javascriptkit.com">JavaScript Kit</a><br>
- <a href="http://www.mindcracker.com/">MindCracker</a><br>
- <a href="http://www.cooltext.com">Cool Text</a><br>
- <a href="http://www.google.com">Google.com</a>
</span> 
<img  src="Image/start.gif"  onclick="SwitchMenu('sub5')"><br>
<span class="submenu" id="sub5">
- <a href="http://www.c-sharpcorner.com/">Link to Us</a><br>
- <a href="http://www.c-sharpcorner.com/Resources/AboutUs.aspx">Know Us</a><br>
- <a href="http://www.c-sharpcorner.com/">Email Us</a><br>
</span>
</
div>
    </form>
</body>

Step 10: In this step we will see the design of the Default2.aspx page which is given below.

img6.gif

Step 11: In this step we are going to run the Default2.aspx page by pressing F5.

img7.gif

Click on every Button; you will see the following output.

img8.gif

img91.gif

img10.gif

img11.gif


img12.gif

Click on the "Link To Us" Button.

img13.gif

Resources