Posts

CSS and jQuery Sliding Drawer Navigation Tutorial

What I'm sharing with you today is a simple jQuery sliding drawer navigation tutorial whereas the sliding drawer looks like and has the same animation effect just like the Android navigation drawer.

We were able to achieve the animation effects with the help of jQuery UI. So in our code, we will see the inclusion of jQuery UI and its CSS URL.

On the webpage, there's a trigger located on the upper left corner, that can show or hide the navigation drawer. You can absolutely customize this to look more like an Android action bar but in our example, I'll use a very simple UI just to get you started.

jquery sliding drawer navigation tutorial
jquery sliding drawer navigation when it is closed or hidden

Why not see it in live demo?

When you click "Show" it will show the navigation drawer panel with animation from left to right, it will reduce the opacity of content and will change the text from "Show" to "Hide".

jQuery Sliding Drawer Navigation Tutorial Step by Step

Prepare your basic HTML code in index.html

<!doctype html>
<html>
    <head>
        <title>jQuery Simple Dropdown Menu</title>
    </head>
<body>
  
</body>
</html>

Add the action-bar div inside the body tag.

<div id='action-bar'>
    <div id='show-drawer'>Show</div>
    <div id='hide-drawer'>Hide</div>
</div>

Put the main-contents div under the action-bar div.

Inside the main-contents div is the navigation-drawer div which will be hidden via CSS, and the 'text-content' div which contains your page content.

The navigation-drawer div may contain anything you want such as list or another divs with the style you want.

<div id='main-contents'>
 
    <div id='navigation-drawer'>
        Drawer contents here.
    </div>
     
    <div id='text-content'>
     
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia non neque et ornare. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur blandit sapien nec iaculis consequat. Nam semper, eros eu tempor bibendum, metus velit scelerisque lorem, non venenatis sem justo non nunc. Cras nec purus eget eros elementum aliquet quis lacinia tortor. Nunc dignissim, purus in gravida tincidunt, quam arcu sodales nisl, nec sollicitudin eros purus vel dui. Etiam erat nunc, faucibus eu pellentesque sed, congue suscipit enim.
        <br /><br />
        Cras sit amet nibh et ante pellentesque malesuada accumsan at turpis. Aliquam ac tellus auctor, sagittis purus eget, venenatis risus. Aenean eget nisl facilisis, tristique est in, fringilla tortor. Pellentesque faucibus aliquam risus. Vestibulum quis vestibulum lectus, sed laoreet nulla. In feugiat, augue at faucibus cursus, metus ligula gravida metus, a condimentum dolor odio vel libero. Curabitur ut viverra orci, eget molestie sem. Aliquam erat volutpat.
        <br /><br />
        Praesent eu viverra sem. Morbi mollis consectetur elit eget pulvinar. Nam nunc nulla, tempus quis sapien id, mattis venenatis purus. Curabitur tortor nulla, vulputate non felis at, vulputate fermentum augue. Sed condimentum egestas metus, non luctus odio consectetur in. Quisque dignissim metus neque, non consequat ligula faucibus id. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nullam varius lacus mi, vel facilisis eros adipiscing ac. Aenean vulputate eros ut sollicitudin lobortis. Vestibulum euismod sollicitudin felis, a ultrices nisi euismod at.
        <br /><br />
        Aliquam hendrerit erat nulla, ut ornare lacus pretium eget. Donec cursus, lectus sed posuere accumsan, metus augue rutrum ligula, a accumsan ipsum turpis suscipit nisl. Morbi id enim sed nisl ornare porttitor. Donec facilisis, nibh eget rhoncus molestie, metus justo rutrum mauris, at mattis quam neque vitae odio. Praesent in nunc ipsum. Cras vulputate lacus sit amet augue cursus viverra. Integer tempor scelerisque lacus, et luctus nunc mollis eget.
        <br /><br />
        Aliquam enim diam, suscipit a metus quis, imperdiet vehicula velit. Pellentesque orci augue, elementum eget eros ut, egestas dictum nunc. Proin vehicula tincidunt velit, eu consequat nunc euismod in. Mauris sit amet ullamcorper sem. Ut et turpis fringilla, volutpat metus quis, rutrum nunc. Ut nisi augue, sagittis eu accumsan adipiscing, blandit at nibh. Vivamus cursus a diam sed pharetra. Nam sed ante iaculis, dictum ipsum id, vulputate purus.
 
    </div>
</div>

Wrap the action-bar and main-contents div inside a page-container div.

<div id='page-container'>
<!-- action-bar and main-contents here -->
</div>

Step 5: Style the page using CSS

We can put the following CSS inside the head tag of our HTML page. Notice that we also added the jQuery UI CSS here.

<!-- jquery ui -->
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css" />
 
<style>
body{
    padding:0;
    margin:0;
    font-family: verdana;
}
 
#action-bar{
    padding:1em;
    border-bottom:0.2em solid #999;
}
 
#main-contents{
    padding:1em;
    position:relative;
}
 
#navigation-drawer{
    border:thin solid #000;
    color:#fff;
    padding:1em;
    position:absolute;
    top:0;
    left:0;
    height:100%;
    background-color:#000;
    display:none;
    z-index:999;
}
 
#hide-drawer{
    display:none;
    cursor:pointer;
}
 
#show-drawer{
    cursor:pointer;
}
</style>

Step 6: Add the jQuery UI and jQuery libraries.

Put them before the end body tag.

<!-- jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 
<!-- jquery ui -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

Add the simple jQuery script that will do the trick

The following code will change the main-contents div height to the current page height so that our navigation-drawer will cover up to the page foot.

The showing or hiding navigation drawer were also done on click event, see the code below.

<script>
$(document).ready(function(){
     
    // so our #navigation-drawer will cover up to the page foot
    $('#main-contents').height($(document).height());
     
    // show the navigation drawer
    $('#show-drawer').click(function(){
 
        $('#text-content').fadeTo('slow', 0.33 );
        $('#navigation-drawer').show('slide', { direction: 'left' }, 300);
         
        $(this).hide();
        $('#hide-drawer').show();
             
    });
     
    // hide the navigation drawer
    $('#hide-drawer').click(function(){
 
        $('#text-content').fadeTo('slow', 1 );
        $('#navigation-drawer').hide('slide', { direction: 'left' }, 300);
         
        $(this).hide();
        $('#show-drawer').show();
             
    });
     
});
</script>

Complete jQuery Sliding Drawer Navigation code

<!doctype html>
<html>
    <head>
        <title>jQuery navigation drawer</title>
         
        <!-- jquery ui -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css" />
 
        <style>
        body{
            padding:0;
            margin:0;
            font-family: verdana;
        }
         
        #action-bar{
            padding:1em;
            border-bottom:0.2em solid #999;
        }
         
        #main-contents{
            padding:1em;
            position:relative;
        }
         
        #navigation-drawer{
            border:thin solid #000;
            color:#fff;
            padding:1em;
            position:absolute;
            top:0;
            left:0;
            height:100%;
            background-color:#000;
            display:none;
            z-index:999;
        }
         
        #hide-drawer{
            display:none;
            cursor:pointer;
        }
         
        #show-drawer{
            cursor:pointer;
        }
        </style>
         
         
    </head>
<body>
 
<div id='page-container'>
 
    <div id='action-bar'>
        <div id='show-drawer'>Show</div>
        <div id='hide-drawer'>Hide</div>
    </div>
 
    <div id='main-contents'>
     
        <div id='navigation-drawer'>
            Drawer contents here.
        </div>
         
        <div id='text-content'>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia non neque et ornare. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur blandit sapien nec iaculis consequat. Nam semper, eros eu tempor bibendum, metus velit scelerisque lorem, non venenatis sem justo non nunc. Cras nec purus eget eros elementum aliquet quis lacinia tortor. Nunc dignissim, purus in gravida tincidunt, quam arcu sodales nisl, nec sollicitudin eros purus vel dui. Etiam erat nunc, faucibus eu pellentesque sed, congue suscipit enim.
            <br /><br />
            Cras sit amet nibh et ante pellentesque malesuada accumsan at turpis. Aliquam ac tellus auctor, sagittis purus eget, venenatis risus. Aenean eget nisl facilisis, tristique est in, fringilla tortor. Pellentesque faucibus aliquam risus. Vestibulum quis vestibulum lectus, sed laoreet nulla. In feugiat, augue at faucibus cursus, metus ligula gravida metus, a condimentum dolor odio vel libero. Curabitur ut viverra orci, eget molestie sem. Aliquam erat volutpat.
            <br /><br />
            Praesent eu viverra sem. Morbi mollis consectetur elit eget pulvinar. Nam nunc nulla, tempus quis sapien id, mattis venenatis purus. Curabitur tortor nulla, vulputate non felis at, vulputate fermentum augue. Sed condimentum egestas metus, non luctus odio consectetur in. Quisque dignissim metus neque, non consequat ligula faucibus id. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nullam varius lacus mi, vel facilisis eros adipiscing ac. Aenean vulputate eros ut sollicitudin lobortis. Vestibulum euismod sollicitudin felis, a ultrices nisi euismod at.
            <br /><br />
            Aliquam hendrerit erat nulla, ut ornare lacus pretium eget. Donec cursus, lectus sed posuere accumsan, metus augue rutrum ligula, a accumsan ipsum turpis suscipit nisl. Morbi id enim sed nisl ornare porttitor. Donec facilisis, nibh eget rhoncus molestie, metus justo rutrum mauris, at mattis quam neque vitae odio. Praesent in nunc ipsum. Cras vulputate lacus sit amet augue cursus viverra. Integer tempor scelerisque lacus, et luctus nunc mollis eget.
            <br /><br />
            Aliquam enim diam, suscipit a metus quis, imperdiet vehicula velit. Pellentesque orci augue, elementum eget eros ut, egestas dictum nunc. Proin vehicula tincidunt velit, eu consequat nunc euismod in. Mauris sit amet ullamcorper sem. Ut et turpis fringilla, volutpat metus quis, rutrum nunc. Ut nisi augue, sagittis eu accumsan adipiscing, blandit at nibh. Vivamus cursus a diam sed pharetra. Nam sed ante iaculis, dictum ipsum id, vulputate purus.
        </div>
         
    </div>
     
</div>
 
<!-- jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 
<!-- jquery ui -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
$(document).ready(function(){
     
    // so our #navigation-drawer will cover up to the page foot
    $('#main-contents').height($(document).height());
     
    // show the navigation drawer
    $('#show-drawer').click(function(){
 
        $('#text-content').fadeTo('slow', 0.33 );
        $('#navigation-drawer').show('slide', { direction: 'left' }, 300);
         
        $(this).hide();
        $('#hide-drawer').show();
             
    });
     
    // hide the navigation drawer
    $('#hide-drawer').click(function(){
 
        $('#text-content').fadeTo('slow', 1 );
        $('#navigation-drawer').hide('slide', { direction: 'left' }, 300);
         
        $(this).hide();
        $('#show-drawer').show();
             
    });
     
});
</script>
 
</body>
</html>

I know it doesn't exactly look like the Android navigation drawer but this code will definitely get you started in doing it. Just play with the HTML and CSS! Hope this jQuery sliding drawer navigation tutorial helps ya!

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

Related Tutorials

Please explore more tutorials on our start page. Click here.

Thank you for learning from our post about CSS and jQuery Sliding Drawer Navigation Tutorial.

Simple jQuery Drop Down Menu Tutorial with Source Code and Live Demo

How are you guys? What I'm sharing today is a simple jQuery drop down menu tutorial that can help you create the simplest of its kind.

This is just to help you get started creating these types of basic website features.

I used this code when I was required to create a drop down menu on the upper right corner of the page. This is what I came up. You can easily change to CSS according to your liking.

simple jquery drop down menu tutorial

You can see the drop down menu on the upper right corner of the image above. But why not see it live? Click the link below.

Simple jQuery Drop Down Menu Tutorial Guide

Prepare basic HTML code.

<!doctype html>
<html>
    <head>
        <title>jQuery Simple Dropdown Menu</title>
        </head>
<body>
 
</body>
</html>

Create the "action-bar" div.

The "action-bar" div is the header bar where a "down arrow" and a "question mark" can be seen on the right side. Put the following inside the body tag.

<div id='action-bar'>
    <span id='question-mark'>
        <div>?</div>
        <div id='under-question-mark'>
            <div class='down-q-item'><a href='#'>Site Map</a></div>
            <div class='down-q-item'><a href='#'>What is this?</a></div>
            <div class='down-q-item'><a href='#'>How to use?</a></div>
            <div class='down-q-item'><a href='#'>Contact Us</a></div>
        </div>
    </span>
    <span id='down-arrow'>
        <div>&#9660;</div>
        <div id='under-down-arrow'>
            <div class='down-q-item'><a href='#'>Print</a></div>
            <div class='down-q-item'><a href='#'>CSV</a></div>
            <div class='down-q-item'><a href='#'>Share</a></div>
        </div>
    </span>
</div>

Create the "main-contents" div.

This "main-contents" div contains whatever contents your page should have. But for this example, we'll have a text content.

<div id='main-contents'>
     
    <div id='text-content'>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia non neque et ornare. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur blandit sapien nec iaculis consequat. Nam semper, eros eu tempor bibendum, metus velit scelerisque lorem, non venenatis sem justo non nunc. Cras nec purus eget eros elementum aliquet quis lacinia tortor. Nunc dignissim, purus in gravida tincidunt, quam arcu sodales nisl, nec sollicitudin eros purus vel dui. Etiam erat nunc, faucibus eu pellentesque sed, congue suscipit enim.
        <br /><br />
        Cras sit amet nibh et ante pellentesque malesuada accumsan at turpis. Aliquam ac tellus auctor, sagittis purus eget, venenatis risus. Aenean eget nisl facilisis, tristique est in, fringilla tortor. Pellentesque faucibus aliquam risus. Vestibulum quis vestibulum lectus, sed laoreet nulla. In feugiat, augue at faucibus cursus, metus ligula gravida metus, a condimentum dolor odio vel libero. Curabitur ut viverra orci, eget molestie sem. Aliquam erat volutpat.
        <br /><br />
        Praesent eu viverra sem. Morbi mollis consectetur elit eget pulvinar. Nam nunc nulla, tempus quis sapien id, mattis venenatis purus. Curabitur tortor nulla, vulputate non felis at, vulputate fermentum augue. Sed condimentum egestas metus, non luctus odio consectetur in. Quisque dignissim metus neque, non consequat ligula faucibus id. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nullam varius lacus mi, vel facilisis eros adipiscing ac. Aenean vulputate eros ut sollicitudin lobortis. Vestibulum euismod sollicitudin felis, a ultrices nisi euismod at.
        <br /><br />
        Aliquam hendrerit erat nulla, ut ornare lacus pretium eget. Donec cursus, lectus sed posuere accumsan, metus augue rutrum ligula, a accumsan ipsum turpis suscipit nisl. Morbi id enim sed nisl ornare porttitor. Donec facilisis, nibh eget rhoncus molestie, metus justo rutrum mauris, at mattis quam neque vitae odio. Praesent in nunc ipsum. Cras vulputate lacus sit amet augue cursus viverra. Integer tempor scelerisque lacus, et luctus nunc mollis eget.
        <br /><br />
        Aliquam enim diam, suscipit a metus quis, imperdiet vehicula velit. Pellentesque orci augue, elementum eget eros ut, egestas dictum nunc. Proin vehicula tincidunt velit, eu consequat nunc euismod in. Mauris sit amet ullamcorper sem. Ut et turpis fringilla, volutpat metus quis, rutrum nunc. Ut nisi augue, sagittis eu accumsan adipiscing, blandit at nibh. Vivamus cursus a diam sed pharetra. Nam sed ante iaculis, dictum ipsum id, vulputate purus.
    </div>
     
</div>

Wrap the "action-bar" and "main-contents" div inside a "page-container" div.

<div id='page-container'>
<!-- action-bar AND main-contents here-->
</div>

Put some CSS styles

Now we have to make our action-bar and main-content look good. We'll put the following CSS inside the header tag, after the title tag.

<style>
body{
    padding:0;
    margin:0;
    font-family: verdana;
}
 
#action-bar{
    border-bottom:0.2em solid #999;
    height:3em;
}
 
#main-contents{
    padding:1em;
    position:relative;
}
 
#down-arrow{
    float:right;
    font-weight: bold;
    padding:0 3em;
    line-height:3em;
    border-left: 2px solid #999;
    border-right: 2px solid #999;
    position:relative;
    cursor:pointer;
}
 
#under-down-arrow{
    z-index: 999;
    position: absolute;
    line-height: 1.5em;
    border: 2px solid #999;
    left: -2px;
    width:6.9em;
    display:none;
}
 
#question-mark{
    float:right;
    font-weight: bold;
    padding:0 3em;
    line-height:3em;
    border-right: 2px solid #999;
    position:relative;
    cursor:pointer;
}
 
#under-question-mark{
    z-index: 999;
    position: absolute;
    line-height: 1.5em;
    border: 2px solid #999;
    left: -2px;
    width:6.6em;
}
 
.down-q-item{
    border-bottom: thin solid #fff;
    padding: .5em .2em;
    background-color: #999;
}
 
.down-q-item a{
    color:#fff;
    text-decoration:none;
    font-size:0.8em;
}
 
.down-q-item:hover{
    background-color: #d1d1d1;
}
</style>

Add the awesome jQuery script

We'll put the jQuery library and some jQuery script before the end body tag. jQuery script is for showing or hiding the drop down menu when the "down arrow" and "question mark" was clicked.

<!-- jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 
<script>
$(document).ready(function(){
 
    $('#down-arrow').click(function(){
        $('#under-down-arrow').slideToggle(200);
    });
 
    $('#question-mark').click(function(){
        $('#under-question-mark').slideToggle(200);
    });
 
});
</script>

Complete jQuery Drop Down Menu Code:

<!doctype html>
<html>
    <head>
        <title>jQuery Simple Dropdown Menu</title>
         
        <style>
        body{
            padding:0;
            margin:0;
            font-family: verdana;
        }
         
        #action-bar{
            border-bottom:0.2em solid #999;
            height:3em;
        }
         
        #main-contents{
            padding:1em;
            position:relative;
        }
         
        #down-arrow{
            float:right;
            font-weight: bold;
            padding:0 3em;
            line-height:3em;
            border-left: 2px solid #999;
            border-right: 2px solid #999;
            position:relative;
            cursor:pointer;
        }
         
        #under-down-arrow{
            z-index: 999;
            position: absolute;
            line-height: 1.5em;
            border: 2px solid #999;
            left: -2px;
            width:6.9em;
            display:none;
        }
         
        #question-mark{
            float:right;
            font-weight: bold;
            padding:0 3em;
            line-height:3em;
            border-right: 2px solid #999;
            position:relative;
            cursor:pointer;
        }
         
        #under-question-mark{
            z-index: 999;
            position: absolute;
            line-height: 1.5em;
            border: 2px solid #999;
            left: -2px;
            width:6.6em;
        }
         
        .down-q-item{
            border-bottom: thin solid #fff;
            padding: .5em .2em;
            background-color: #999;
        }
         
        .down-q-item a{
            color:#fff;
            text-decoration:none;
            font-size:0.8em;
        }
         
        .down-q-item:hover{
            background-color: #d1d1d1;
        }
        </style>
         
         
    </head>
<body>
 
<div id='page-container'>
 
    <div id='action-bar'>
        <span id='question-mark'>
            <div>?</div>
            <div id='under-question-mark'>
                <div class='down-q-item'><a href='#'>Site Map</a></div>
                <div class='down-q-item'><a href='#'>What is this?</a></div>
                <div class='down-q-item'><a href='#'>How to use?</a></div>
                <div class='down-q-item'><a href='#'>Contact Us</a></div>
            </div>
        </span>
        <span id='down-arrow'>
            <div>&#9660;</div>
            <div id='under-down-arrow'>
                <div class='down-q-item'><a href='#'>Print</a></div>
                <div class='down-q-item'><a href='#'>CSV</a></div>
                <div class='down-q-item'><a href='#'>Share</a></div>
            </div>
        </span>
    </div>
 
    <div id='main-contents'>
         
        <div id='text-content'>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum lacinia non neque et ornare. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur blandit sapien nec iaculis consequat. Nam semper, eros eu tempor bibendum, metus velit scelerisque lorem, non venenatis sem justo non nunc. Cras nec purus eget eros elementum aliquet quis lacinia tortor. Nunc dignissim, purus in gravida tincidunt, quam arcu sodales nisl, nec sollicitudin eros purus vel dui. Etiam erat nunc, faucibus eu pellentesque sed, congue suscipit enim.
            <br /><br />
            Cras sit amet nibh et ante pellentesque malesuada accumsan at turpis. Aliquam ac tellus auctor, sagittis purus eget, venenatis risus. Aenean eget nisl facilisis, tristique est in, fringilla tortor. Pellentesque faucibus aliquam risus. Vestibulum quis vestibulum lectus, sed laoreet nulla. In feugiat, augue at faucibus cursus, metus ligula gravida metus, a condimentum dolor odio vel libero. Curabitur ut viverra orci, eget molestie sem. Aliquam erat volutpat.
            <br /><br />
            Praesent eu viverra sem. Morbi mollis consectetur elit eget pulvinar. Nam nunc nulla, tempus quis sapien id, mattis venenatis purus. Curabitur tortor nulla, vulputate non felis at, vulputate fermentum augue. Sed condimentum egestas metus, non luctus odio consectetur in. Quisque dignissim metus neque, non consequat ligula faucibus id. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nullam varius lacus mi, vel facilisis eros adipiscing ac. Aenean vulputate eros ut sollicitudin lobortis. Vestibulum euismod sollicitudin felis, a ultrices nisi euismod at.
            <br /><br />
            Aliquam hendrerit erat nulla, ut ornare lacus pretium eget. Donec cursus, lectus sed posuere accumsan, metus augue rutrum ligula, a accumsan ipsum turpis suscipit nisl. Morbi id enim sed nisl ornare porttitor. Donec facilisis, nibh eget rhoncus molestie, metus justo rutrum mauris, at mattis quam neque vitae odio. Praesent in nunc ipsum. Cras vulputate lacus sit amet augue cursus viverra. Integer tempor scelerisque lacus, et luctus nunc mollis eget.
            <br /><br />
            Aliquam enim diam, suscipit a metus quis, imperdiet vehicula velit. Pellentesque orci augue, elementum eget eros ut, egestas dictum nunc. Proin vehicula tincidunt velit, eu consequat nunc euismod in. Mauris sit amet ullamcorper sem. Ut et turpis fringilla, volutpat metus quis, rutrum nunc. Ut nisi augue, sagittis eu accumsan adipiscing, blandit at nibh. Vivamus cursus a diam sed pharetra. Nam sed ante iaculis, dictum ipsum id, vulputate purus.
        </div>
         
    </div>
     
</div>
 
<!-- jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
 
<script>
$(document).ready(function(){
 
    $('#down-arrow').click(function(){
        $('#under-down-arrow').slideToggle(200);
    });
 
    $('#question-mark').click(function(){
        $('#under-question-mark').slideToggle(200);
    });
 
});
</script>
 
</body>
</html>

As you can see, instead of using a jQuery plugin or something that can slow down your website, you can just create your own thing. This simple jQuery drop down menu tutorial is an example.

There are many improvements or customization that you can do to this example code, I'll let you play with it, jQuery and CSS is fun, right?. I hope I got you started!

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

Related Tutorials

Please explore more tutorials on our start page. Click here.

Thank you for learning from our post about Simple jQuery Drop Down Menu Tutorial!

jQuery Tutorial for Beginners – Step By Step Guide!

jquery-step-by-step-tutorial-for-beginners

Previously, we learned how to use Bootstrap to make our web applications look good. This time, we will learn how to use jQuery.

Many of you asked me how to use jQuery. This tutorial is my answer to you. I want to give you links but I feel like it's easier to teach someone about something that is your own version of work! We hope you guys will find this step by step guide useful.

Getting Started with jQuery

What is jQuery? Okay here’s the simplest definition I can give. jQuery is a JavaScript library. It can:

  1. Make your JavaScript code shorter, faster and cross browser.
  2. Manipulate your HTML, like showing or hiding something from the page.
  3. Handles events – it can do something when a user click a button or any other activity a user can do with a mouse.
  4. Animation – for example make a part of your page fade in, fade out or just simply make something move.
  5. AJAX – do a server request without refreshing your whole web page.

This post. I assume you already know basic HTML, CSS and JavaScript. In this post, aside from the simple definition of jQuery above, we are just going to have two parts:

  1. The super straightforward, step by step tutorial or guide in running a very basic jQuery script. (2.0)
  2. We are going to take a look more of the jQuery basic concepts, as shown in #1 (3.0)

Run jQuery in 5 Easy Steps

Follow the steps below – these steps will lead you to run a very basic jQuery script that does a slide and toggle.

Create HTML page with its basic structure.

<!-- step 1 -->
<!DOCTYPE html>
<html>
<head>
    <title>jQuery Tutorial for Beginners</title>
</head>
<body>
 
</body>
</html>

Add element to be clicked. We’re gonna have a button in this example, we added an ID name to this button called myButton. Add the following code inside the "body" tag.

<!-- step 2 -->
<button id='myButton'>Click to Slide or Toggle</button>

Add the element to be shown or hidden. We’re gonna have a "p" tag with bunch of sample words inside. Add the following code below step 2′s code.

<!-- step 3 -->
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec.
</p>

Add the jQuery library. Aren’t you excited? You can also download your own copy of jQuery but in today’s example, we’ll be linking to Google’s copy of jQuery. Add the following code below step 3′s code.

<!-- step 4 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

Step 5: Add jQuery script. This script will show or hide the "p" tag and the words inside it. Notice that we selected the button by referencing our button’s ID myButton.

<!-- step 5 -->
<script>
$("#myButton").click(function () {
    $("p").slideToggle("slow");
});
</script>

Download Source Codes

You can download all the code used in this tutorial for only $9.99 $5.55!

Congratulations! You are now a jQuery coder! Just kidding. Not yet. But don’t lose hope!

To achieve being a real jQuery coder, like any other skill, it must be practiced and be well versed with its concepts. So continue to read below and make your jQuery wisdom a little bit better.jQuery Basic Concepts

4.1 Run jQuery when DOM is ready. We didn’t implement this in our example above because I want to give you a quick look on how to run a jQuery script and it is a very small web page anyway.

But in reality, if you use jQuery in larger web pages, you have to run it when the DOM is ready. Here’s how:

$(document).ready(function() {
    // jQuery will run once everthing else in your web page is already loaded.
    // All your jQuery codes here.
});

How to Select an Element in jQuery? Learning jQuery selectors are very important because you’re dealing with HTML elements within your web page.

I’m gonna give you some of the most basic selectors being used:

// selects 'only one' HTML element with ID "myButton", such as our example above
// notice that we use hashes (#) for ids, like that of CSS
$("#myButton");
 
// selects all HTML elements with class "myClass", for instance: <div class='myClass'></div>
// notice that we used dots (.) for classes, like that of CSS
$(".myClass");
 
// selects all button HTML element, for example: <button>Click Me!</button>
$("button");
 
// selects all div element, example: <div>Me and all other div will be selected!</div>
$("div");
 
// selects all anchor link element, for example: <a href="https://codeofaninja.com/">Me and all other 'a' tags will be selected!</a>
$("a");

Learn more jQuery Selectors

jQuery Events. In our example above (2.0), we use a click event, in jQuery it was represented by the click() method. Here are some more jQuery events that you might find useful:

$("button").click(function(){
    // do something when user click the button
});
 
$("form").submit(function(){
    // do something when user submits a form
});
 
$("#myDiv").hover(function(){
    // do something when user hover an HTML element
});
 
$("#myTextbox").keyup(function(){
    // do something when user types on a textbox with ID myTextbox
});

Learn more jQuery Events

Animation Effects with jQuery. On our example above (2.0), the animation effect we used is the slideToggle(). Here are some other animations that you can do with jQuery:

// slide or toggle animation with a <p> tag
// you can change 'slow' to 'fast' or any number in milliseconds
$("p").slideToggle("slow");
 
$("p").slideToggle(1000, function() {  
    // do something when slide up or down animation is done
});
 
// hide the matched elements with a sliding motion.
$( "#book" ).slideUp( "slow", function() {
    // animation complete
});
 
// display or hide the matched elements by animating their opacity.
$( "#book" ).fadeToggle( "fast", function() {
    // animation complete
});

Learn more jQuery Animation Effect

Remember that the examples above are just some of the basics. Continue to practice, search and learn more in the process. And as always, thanks for reading!

5.0 Online Resources

6.0 What's Next?

Learn jQuery UI Tutorial for Beginners - Learn how to use date picker and other user interface interactions, effects, widgets, and themes built on top of the jQuery.

7.0 Related Tutorials

Please explore more tutorials on our start page. Click here.

8.0 Some Notes

Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

Subscribe to CodeOfaNinja

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

Thank You!

Thank you for learning with our jQuery Tutorial for Beginners! Please share this tutorial to one of your friends if you have time.

jQuery AJAX Post Example with PHP and JSON

RELATED TUTORIAL: PHP, MySQL and AJAX CRUD Tutorial – Step by Step Guide!

Today I’m gonna give you some code examples on how you can post a form and JSON data using jQuery AJAX.

A PHP file will receive the posted data and print the response.

I think this is one of the most useful code when you’re coding with jQuery, especially if you’re building a web app with modules that deals with so many forms or post request in one page.

Why use jQuery for AJAX requests?

I think it is to make things easier, have shorter more readable code. You can see some code examples of doing an AJAX request without jQuery here and here.

As you can see on those links, some tasks include creating a catch for different browser XMLHttpRequest, opening the url, checking if the request is in ready state and setting the request header.

jQuery solves this by having a short, more readable syntax.

Let’s code!

Alright, now we’ll get straight to the code examples. We’re gonna have three example below, continue to read!

jQuery post form data using .ajax() method

This is a great way to show someone that you are now an AJAX programmer. Because of this .ajax() piece of code in your HTML page, you may now face the world with confidence and with a beautiful smile in your face.

Just kidding. But seriously, this piece of code is useful.

<html>
    <head>
        <title>jQuery post form data using .ajax() method by codeofaninja.com</title>
         
    </head>
<body>
 
<h1>jQuery post form data using .ajax() method</h1>
<div>Fill out and submit the form below to get response.</div>
 
<!-- our form -->  
<form id='userForm'>
    <div><input type='text' name='firstname' placeholder='Firstname' /></div>
    <div><input type='text' name='lastname' placeholder='Lastname' /></div>
    <div><input type='text' name='email' placeholder='Email' /></div>
    <div><input type='submit' value='Submit' /></div>
</form>
 
<!-- where the response will be displayed -->
<div id='response'></div>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
    $('#userForm').submit(function(){
     
        // show that something is loading
        $('#response').html("<b>Loading response...</b>");
         
        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.ajax({
            type: 'POST',
            url: 'post_receiver.php', 
            data: $(this).serialize()
        })
        .done(function(data){
             
            // show the response
            $('#response').html(data);
             
        })
        .fail(function() {
         
            // just in case posting your form failed
            alert( "Posting failed." );
             
        });
 
        // to prevent refreshing the whole page page
        return false;
 
    });
});
</script>
 
</body>
</html>

jQuery post form data using .post() method

.post() method has a more descriptive syntax, it is a shorthand of .ajax() method above. See how it was commonly used with the code below:

<html>
    <head>
        <title>jQuery post form data using .post() method by codeofaninja.com</title>
         
    </head>
<body>
 
<h1>jQuery post form data using .post() method</h1>
<div>Fill out and submit the form below to get response.</div>
 
<!-- our form -->  
<form id='userForm'>
    <div><input type='text' name='firstname' placeholder='Firstname' /></div>
    <div><input type='text' name='lastname' placeholder='Lastname' /></div>
    <div><input type='text' name='email' placeholder='Email' /></div>
    <div><input type='submit' value='Submit' /></div>
</form>
 
<!-- where the response will be displayed -->
<div id='response'></div>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
    $('#userForm').submit(function(){
     
        // show that something is loading
        $('#response').html("<b>Loading response...</b>");
         
        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.post('post_receiver.php', $(this).serialize(), function(data){
             
            // show the response
            $('#response').html(data);
             
        }).fail(function() {
         
            // just in case posting your form failed
            alert( "Posting failed." );
             
        });
 
        // to prevent refreshing the whole page page
        return false;
 
    });
});
</script>
 
</body>
</html>

jQuery post JSON data using .post() method

Sometimes you don’t want to post data from an HTML form. You can do it by creating a JSON string, and here’s how you’ll be able to post it.

<html>
    <head>
        <title>jQuery post JSON data using .post() method by codeofaninja.com</title>
         
    </head>
<body>
 
<h1>jQuery post JSON data using .post() method</h1>
<div>Click the button below to get response.</div>
 
<!-- our form -->  
<input type='button' value='Post JSON' id='postJson' />
 
<!-- where the response will be displayed -->
<div id='response'></div>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
 
    $('#postJson').click(function(){
     
        // show that something is loading
        $('#response').html("<b>Loading response...</b>");
         
        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.post('post_receiver.php', { user_id: "143", username: "ninjazhai", website: "https://codeofaninja.com/" }, function(data){
             
            // show the response
            $('#response').html(data);
             
        }).fail(function() {
         
            // just in case posting your form failed
            alert( "Posting failed." );
             
        });
 
        // to prevent refreshing the whole page page
        return false;
 
    });
});
</script>
 
</body>
</html>

Posting a JSON string using the .ajax() method is also possible, you can just replace the serialize() part with your JSON string.

Posted Data

Where did the posted data go? To the file where you want the posted data to be processed! But in our example, we just print the posted data. post_receiver.php has the following code

<?php
echo "<pre>";
    print_r($_POST);
echo "</pre>";
?>

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

If you want to learn how to create, read, update and delete data with AJAX, go ahead and learn from our AJAX CRUD Tutorial Using jQuery, JSON and PHP – Step by Step Guide!.

Related Tutorials

Please explore more tutorials on our start page. Click here.

Thank you for learning our post about jQuery AJAX Post Example with PHP and JSON!

RELATED TUTORIAL: PHP, MySQL and AJAX CRUD Tutorial – Step by Step Guide!

jQuery: Sum TextBox Values As You Type

A friend asked me how to sum all TextBox value as he type the numbers?

Here’s a quick answer to that:

Give all your TextBoxes a class name and use the jQuery ‘keyup()’ and ‘each()’ methods to compute the sum.

HTML - a table where the product name and price TextBox is found.

<table>
    <tr>
        <td>Product Name</td>
        <td>Price</td>
    </tr>
     
    <tr>
        <td>MOBILE POWER BANK (2800MAH)</td>
        <td><input type='text' class='price' /></td>
    </tr>
     
    <tr>
        <td>DISNEY NECK REST PILLOW (CHIP)</td>
        <td><input type='text' class='price' /></td>
    </tr>
     
    <tr>
        <td></td>
        <td><input type='text' id='totalPrice' disabled /></td>
    </tr>
</table>

jQuery - methods we used include keyup, each and val. Read comments on code.

<script>
// we used jQuery 'keyup' to trigger the computation as the user type
$('.price').keyup(function () {
 
    // initialize the sum (total price) to zero
    var sum = 0;
     
    // we use jQuery each() to loop through all the textbox with 'price' class
    // and compute the sum for each loop
    $('.price').each(function() {
        sum += Number($(this).val());
    });
     
    // set the computed value to 'totalPrice' textbox
    $('#totalPrice').val(sum);
     
});
</script>

Complete Code:

<html>
    <head>
        <title>jQuery Sum Demo</title>
    </head>
<body>
 
<table>
    <tr>
        <td>Product Name</td>
        <td>Price</td>
    </tr>
     
    <tr>
        <td>MOBILE POWER BANK (2800MAH)</td>
        <td><input type='text' class='price' /></td>
    </tr>
     
    <tr>
        <td>DISNEY NECK REST PILLOW (CHIP)</td>
        <td><input type='text' class='price' /></td>
    </tr>
     
    <tr>
        <td></td>
        <td><input type='text' id='totalPrice' disabled /></td>
    </tr>
</table>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
 
<script>
// we used jQuery 'keyup' to trigger the computation as the user type
$('.price').keyup(function () {
 
    // initialize the sum (total price) to zero
    var sum = 0;
     
    // we use jQuery each() to loop through all the textbox with 'price' class
    // and compute the sum for each loop
    $('.price').each(function() {
        sum += Number($(this).val());
    });
     
    // set the computed value to 'totalPrice' textbox
    $('#totalPrice').val(sum);
     
});
</script>
 
</body>
</html>

This post will be updated if any variation occurs. :)

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

Related Tutorials

Please explore more tutorials on our start page. Click here.

Thank you for learning from our post about Sum TextBox Values As You Type in jQuery.

Two Example Usage of jQuery On() Method

How are you guys? Many friends asks me what is the use of jQuery on() method, where and when can we use it and why is it important.

So in this tutorial, I’m going to give you two example situations where we can use the jQuery on() method.

"Home

By definition, jQuery on() method attaches an event handler function (click, submit, etc.) to one or more elements (div, p, etc.). In my experience, I used jQuery on() when:

  • I want to load a new HTML form on a DIV and submit it without page refresh.
  • I want to reload a list of records and use the actions like ‘Delete’.

By the way, you can download all the codes used in this post:

Loading Different Forms to a DIV

This code can load the ‘Add User’ and ‘Add Role’ form to the ‘formContainer’ DIV (one at a time). Our goal is to submit the form without page refresh. To achieve that we are going to use the on() method. See the live demo:

form_w_on.php code:

<html>
    <head>
        <title>jQuery On() Tutorial - submit with on()</title>
     
        <style>
        #addNewUser, #addNewRole{
            cursor:pointer;
            float:left;
            text-decoration:underline;
        }
         
        #formContainer{
            border:thin solid #000;
            padding:0.5em;
            margin:1em 0 0 0;
        }
         
        .clearBoth{
            clear:both;
        }
        </style>
         
    </head>
<body>
 
<div id='addNewUser'>[+ New User]</div>
<div id='addNewRole'>[+ New Roles]</div>
 
<div class='clearBoth'></div>
 
<div id='formContainer'>
    <!--here is where the form will be loaded -->
</div>
 
<script src='js/jquery-1.9.1.min.js'></script>
<script>
$(document).ready(function(){
 
    // when user clicks '[+ New User]', it will load the add_user.php file
    $('#addNewUser').click(function(){
         
        $('#formContainer').load('add_user.php', function(){
            console.log('user form loaded!');
        });
         
    });
     
    // when user clicks '[+ New Roles]', it will load the add_role.php file
    $('#addNewRole').click(function(){
        $('#formContainer').load('add_role.php', function(){
            console.log('role form loaded!');
        });
    });
     
    // when the user submits the 'add new user' form
    $(document).on('submit', '#addUserForm', function(){ 
        alert('Add new user form is submitted!');
        return false;
    });
 
    // when the user submits the 'add new role' form
    $(document).on('submit', '#addRoleForm', function(){ 
        alert('Add new role form is submitted!');
        return false;
    });
     
     
});
</script>
 
</body>
</html>

add_user.php code:

<form id='addUserForm'>
    <div>Firstname: <input type='text' name='firstname' /></div>
    <div>Lastname: <input type='text' name='lastname' /></div>
    <div><input type='submit' value='Save' /></div>
</form>

add_role.php code:

<form id='addRoleForm'>
    <div>User Role: <input type='text' name='role' /></div>
    <div>Description: <input type='text' name='description' /></div>
    <div><input type='submit' value='Save' /></div>
</form>

Without the on() method, jQuery code usually looks like this (form_w_out_on.php):

<script>
$(document).ready(function(){
 
    // when user clicks '[+ New User]', it will load the add_user.php file
    $('#addNewUser').click(function(){
         
        $('#formContainer').load('add_user.php', function(){
            console.log('user form loaded!');
        });
         
    });
     
    // when user clicks '[+ New Roles]', it will load the add_role.php file
    $('#addNewRole').click(function(){
        $('#formContainer').load('add_role.php', function(){
            console.log('role form loaded!');
        });
    });
     
    // when the user submits the 'add new user' form
    $('#addUserForm').submit(function() {
        alert('Add user form is submitted!');
        return false;
    });
 
    // when the user submits the 'add new role' form
    $('#addRoleForm').submit(function() {
        alert('Add new role form is submitted!');
        return false;
    });
     
});
</script>

Here’s a live demo without using the on() method, it reloads the whole page.

Loading Table List to a DIV

jquery-on-tutorial---load-table-list

In this example, when the user clicks on the “[Load List]” text, it will load a table list of data (list.php) with a ‘Delete’ action right across each records.

index.php code:

<html>
    <head>
        <title>jQuery on() tutorial - loading lists</title>
         
        <style>
        #myTable{
            float:left;
            margin:1em 0 0 0;
        }
         
        #myTable th, 
        #myTable td{
            border:thin solid #000;
            padding:1em;
        }
         
        .deleteAction{
            cursor:pointer;
        }
         
        #loadAction{
            cursor:pointer;
            text-decoration:underline;
        }
        </style>
         
    </head>
<body>
 
<div id='loadAction'>[Load List]</div>
 
<div id='listContainer'>
    <!--here is where the form will be loaded -->
</div>
 
<script src='js/jquery-1.9.1.min.js'></script>
<script>
$(document).ready(function(){
 
    $('#loadAction').click(function(){
         
        $('#listContainer').load('list.php', function(){
            console.log('list loaded!');
        });
         
    });
     
    /*
    // using this code won't pop up 'Are you sure?'
    $('.deleteAction').click(function(){
        if(confirm('Are you sure?'){
 
             // do things if ok
 
        }
    });
    */
     
    $(document).on('click', '.deleteAction', function(){ 
        if(confirm('Are you sure?')){
 
             // do things if ok
 
        }
    });
     
});
</script>
 
 
</body>
</html>

Similarly, as indicated in the code comments, ‘Are you sure?’ alert dialog won’t be shown without the help of the jQuery on() method.

list.php – the data to be loaded in the listContainer div.

<table id='myTable'>
    <tr>
        <th>Name</th>
        <th>Action</th>
    </tr>
    <tr>
        <td>Mike Dalisay</td>
        <td>
            <div class='deleteAction'>Delete</div>
        </td>
    </tr>
    <tr>
        <td>Marykris De Leon</td>
        <td>
            <div class='deleteAction'>Delete</div>
        </td>
    </tr>
</table>

There are other previously used methods almost similar the jQuery on(), like live() and delegate(). But among those methods, jQuery on() is recommended to use (if you’re using jQuery 1.7+). Users of older versions of jQuery should use delegate() in preference to live().

If you want to read more about this topic,here are some links that can help.

Download Source Codes
You can download all the code used in this tutorial for only $9.99 $5.55!

Related Tutorials

Please explore more tutorials on our start page. Click here.

A Quick Way To Create A Vertical Accordion With jQuery

Today we are going to create a vertical accordion from scratch, using jQuery of course!

We will have few lines of code that would be easy to understand.

I used this code when I was asked to create an accordion for a website’s headlines.

A Quick Way To Create A Vertical Accordion With jQuery

So in this example code, we will have:

  • Three headlines, one headline is opened on load by default.
  • When a use clicks on a headline with hidden content, it will slide down the hidden content to be shown and close (slide up) the previously opened headline.

CSS – You may do your tweaks to design your own accordion (change colors, add images, etc.) but make sure the main style are the following.

body {
    font-family:Georgia, serif;
}
 
.headlineTitle {
    font-weight:bold;
    padding:5px 0;
}
 
.item {
    border:thin solid #c0c0c0;;
    margin:0 0 0.5em 0;
}
 
.itemContents {
    display:none;
    margin:.05em 0 0 0;
    padding:10px;
}
 
.itemTitle {
    background-color:#FAEBD7;
    cursor:pointer;
    font-weight:bold;
    padding:10px;
}
 
.openedContent {
    display:block;
}

HTML - Our html scructure would look like this. This could be generated multiple times by your server side script like PHP (reading records from a database), but in this example, we are using static HTML.

<div class="itemsContainer">
<div class="item">
    <div class="itemTitle opened">First Headline</div>
    <div class="itemContents openedContent">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eu elit dui, sed dapibus ante. Donec fermentum, metus et convallis vulputate, justo mauris viverra mauris, ut dictum nisi eros sit amet ante. Suspendisse velit erat, iaculis a feugiat sed, pretium eu magna. Praesent pharetra nisi eu odio bibendum dapibus. Nullam sollicitudin auctor vulputate. Fusce ultrices molestie justo et feugiat. Aenean elit tortor, scelerisque quis ultricies in, pharetra quis quam.
    </div>
</div>
<div class="item">
    <div class="itemTitle">Second Headline</div>
    <div class="itemContents">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eu elit dui, sed dapibus ante. Donec fermentum, metus et convallis vulputate, justo mauris viverra mauris, ut dictum nisi eros sit amet ante. Suspendisse velit erat, iaculis a feugiat sed, pretium eu magna. Praesent pharetra nisi eu odio bibendum dapibus. Nullam sollicitudin auctor vulputate. Fusce ultrices molestie justo et feugiat. Aenean elit tortor, scelerisque quis ultricies in, pharetra quis quam.
    </div>
</div>

jQuery – makes our accordion work with few lines of codes.

$('.itemTitle').click(function () {
 
    // show the content only if it is hidden        
    if ($(this).closest('.item').find('.itemContents').is(":hidden")) {
     
        //open the content          
        $(this).closest('.item').find('.itemContents').slideDown("fast");
         
        //close previously opened content           
        $(this).closest('.itemsContainer').find('.opened').closest('.item').find('.itemContents').slideUp("fast");
         
        // remove the "opened" class from previously opened content         
        $(this).closest('.itemsContainer').find('.opened').removeClass('opened');
         
        //add class to mark the clicked item is opened          
        $(this).addClass("opened");
    }
});

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

Related Tutorials

Please explore more tutorials on our start page. Click here.

jQuery slideToggle Example – Solution to Table Row’s Long List of Options

When building a web application, there are some situations where you want to have long list options for a table row data.

This is where jQuery slideToggle example will be very useful.

In our example for today, I have a list of “Authors”, I wanna have the ability to go to their websites, list of articles, or social networking links easily when the list is shown.

But of course, the “Options” column space is limited.

I have something to introduce to you, a company called "Small Tree," where they design for collaborative editing teams, they provides post production workflow solutions that combine the highest possible performance, ease of use, and reliability, backed by their industry-leading technical support.

Solving Your Table Row Data’s Long List Of Options

Here is how I solved it.

  • I only put three options on the first load. As you can see we have “Edit”, “Delete” and “More” options.
  • The “More” options which is highlighted in “green” will give the user a cue that it can be clicked and more options will be shown, it will beautifully animate to show “more options”.
  • “More” text will become “Less” and will be highlighted in “red” which will give the user a cue that you can hide the options.
other-options-were-shown

CSS code – styling our table.

body{
    font-family:arial,sans-serif;
}

table a{
    color:#039;
    font-weight:bold;
    text-decoration:none;
}

table a:hover{
    color:#000;
    font-weight:bold;
}

th {
    background-color:#b9c9fe;
    color:#039;
    padding: 10px;
}

td {
    background-color:#e8edff;
    padding: 10px;
}

.verticalOption{
    margin:8px 0;
}

.moreOptionsLink{
    background-color:green;
    color:#fff;
    padding: 0 2px;
}

.moreOptionsLink:hover{
    color:#fff;
}

.moreOptions{
    display:none;
}

HTML code – we are using static HTML in this example, in the real world, this HTML should be generated dynamically.

<!-- our example table -->
<table border='0' cellpadding='2'>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
        <th>Username</th>
        <th>Options</th>
    </tr>
    <tr>
        <td>JM</td>
        <td>Dalisay</td>
        <td>[email protected]</td>
        <td>dalisay</td>
        <td>
            <!-- It is important to understand our "Options" HTML structure. -->
            <a href="">Edit</a> /
            <a href="">Delete</a> /
            <a href="" class="moreOptionsLink">More</a>

            <!--
                Here are the hidden "moreOptions"
                    which will be shown when "More" was clicked
                    and hidden when "Less" was clicked
            -->
            <div class="moreOptions">
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Articles</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">View Online</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Website</a>
                </div>
                <div class="verticalOption">
                    <a href="https://www.facebook.com/CodeOfANinja" target="_blank">Facebook</a>
                </div>
                <div class="verticalOption">
                    <a href="http://twitter.com/ninjazhai" target="_blank">Twitter</a>
                </div>
                <div class="verticalOption">
                    <a href="https://plus.google.com/103126728967620382717" target="_blank">Google+</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">LinkedIn</a>
                </div>
            </div>
        </td>
    </tr>
    <!-- more table rows should be here -->
</table>

jQuery code – the animation and magic. :)

<!-- include our jQuery -->
<script src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){

    // when "More" or "Less" (class moreOptionsLink) was clicked.
    $(".moreOptionsLink").click(function(){

        var txt = $(this).text();

        if(txt=='More'){
            /*
             * change the text to "Less"
             * change the background color to "red"
             * which means it shows all the options
             */
            $(this).text('Less');
            $(this).css("background-color","red");
        }

        else{
            /*
             * change the text to "More"
             * change the background color to "green"
             * which means it hides other options
             */
            $(this).text('More');
            $(this).css("background-color","green");
        }

        /*
         * to animate the container of other options
         * we use jQuery "next" to select the "moreOptions" of the current row
         */
        $(this).next(".moreOptions").slideToggle("fast");

        // so that it won't refresh the page
        return false;
    });
});
</script>

Codes combined:

<html>
<head>
    <title>A Way To Solve Long List Of Options Of Your Table Row Data</title>

    <!-- just some styling -->
    <style>
    body{
        font-family:arial,sans-serif;
    }

    table a{
        color:#039;
        font-weight:bold;
        text-decoration:none;
    }

    table a:hover{
        color:#000;
        font-weight:bold;
    }

    th {
        background-color:#b9c9fe;
        color:#039;
        padding: 10px;
    }

    td {
        background-color:#e8edff;
        padding: 10px;
    }

    .verticalOption{
        margin:8px 0;
    }

    .moreOptionsLink{
        background-color:green;
        color:#fff;
        padding: 0 2px;
    }

    .moreOptionsLink:hover{
        color:#fff;
    }

    .moreOptions{
        display:none;
    }

    </style>
</head>
<body>

<!-- our example table -->
<table border='0' cellpadding='2'>
    <tr>
        <th>Firstname</th>
        <th>Lastname</th>
        <th>Email</th>
        <th>Username</th>
        <th>Options</th>
    </tr>
    <tr>
        <td>JM</td>
        <td>Dalisay</td>
        <td>[email protected]</td>
        <td>dalisay</td>
        <td>
            <!-- It is important to understand our "Options" HTML structure. -->
            <a href="">Edit</a> /
            <a href="">Delete</a> /
            <a href="" class="moreOptionsLink">More</a>

            <!--
                Here are the hidden "moreOptions"
                    which will be shown when "More" was clicked
                    and hidden when "Less" was clicked
            -->
            <div class="moreOptions">
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Articles</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">View Online</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Website</a>
                </div>
                <div class="verticalOption">
                    <a href="https://www.facebook.com/CodeOfANinja" target="_blank">Facebook</a>
                </div>
                <div class="verticalOption">
                    <a href="http://twitter.com/ninjazhai" target="_blank">Twitter</a>
                </div>
                <div class="verticalOption">
                    <a href="https://plus.google.com/103126728967620382717" target="_blank">Google+</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">LinkedIn</a>
                </div>
            </div>
        </td>
    </tr>
    <tr>
        <td>Edward</td>
        <td>Morden</td>
        <td>[email protected]</td>
        <td>edward</td>
        <td>
            <a href="">Edit</a> /
            <a href="">Delete</a> /
            <a href="" class="moreOptionsLink">More</a>
            <div class="moreOptions">
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Articles</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">View Online</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Website</a>
                </div>
                <div class="verticalOption">
                    <a href="https://www.facebook.com/CodeOfANinja" target="_blank">Facebook</a>
                </div>
                <div class="verticalOption">
                    <a href="http://twitter.com/ninjazhai" target="_blank">Twitter</a>
                </div>
                <div class="verticalOption">
                    <a href="https://plus.google.com/103126728967620382717" target="_blank">Google+</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">LinkedIn</a>
                </div>
            </div>
        </td>
    </tr>
    <tr>
        <td>Vanessa</td>
        <td>Hudgens</td>
        <td>[email protected]</td>
        <td>vanessa</td>
        <td>
            <a href="">Edit</a> /
            <a href="">Delete</a> /
            <a href="" class="moreOptionsLink">More</a>
            <div class="moreOptions">
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Articles</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">View Online</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Website</a>
                </div>
                <div class="verticalOption">
                    <a href="https://www.facebook.com/CodeOfANinja" target="_blank">Facebook</a>
                </div>
                <div class="verticalOption">
                    <a href="http://twitter.com/ninjazhai" target="_blank">Twitter</a>
                </div>
                <div class="verticalOption">
                    <a href="https://plus.google.com/103126728967620382717" target="_blank">Google+</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">LinkedIn</a>
                </div>
            </div>
        </td>
    </tr>
    <tr>
        <td>Michael</td>
        <td>Jackson</td>
        <td>[email protected]</td>
        <td>michael</td>
        <td>
            <a href="">Edit</a> /
            <a href="">Delete</a> /
            <a href="" class="moreOptionsLink">More</a>
            <div class="moreOptions">
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Articles</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">View Online</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">Website</a>
                </div>
                <div class="verticalOption">
                    <a href="https://www.facebook.com/CodeOfANinja" target="_blank">Facebook</a>
                </div>
                <div class="verticalOption">
                    <a href="http://twitter.com/ninjazhai" target="_blank">Twitter</a>
                </div>
                <div class="verticalOption">
                    <a href="https://plus.google.com/103126728967620382717" target="_blank">Google+</a>
                </div>
                <div class="verticalOption">
                    <a href="https://codeofaninja.com/" target="_blank">LinkedIn</a>
                </div>
            </div>
        </td>
    </tr>
</table>

<!-- include our jQuery -->
<script src="js/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){

    // when "More" or "Less" (class moreOptionsLink) was clicked.
    $(".moreOptionsLink").click(function(){

        var txt = $(this).text();

        if(txt=='More'){
            /*
             * change the text to "Less"
             * change the background color to "red"
             * which means it shows all the options
             */
            $(this).text('Less');
            $(this).css("background-color","red");
        }

        else{
            /*
             * change the text to "More"
             * change the background color to "green"
             * which means it hides other options
             */
            $(this).text('More');
            $(this).css("background-color","green");
        }

        /*
         * to animate the container of other options
         * we use jQuery "next" to select the "moreOptions" of the current row
         */
        $(this).next(".moreOptions").slideToggle("fast");

        // so that it won't refresh the page
        return false;
    });
});
</script>

</body>
</html>

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

Related Tutorials

Please explore more tutorials on our start page. Click here.

Thank you for learning from our post about jQuery slideToggle Example - Solution Row's Long List of Options!