JavaScript sliding panel tutorial

What I'm sharing with you today is a simple JavaScript sliding panel 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

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!
[purchase_link id="12272" text="Download Now" style="button" color="green"]

Related Tutorials

We listed all our high quality full-stack web development tutorials here: Click here.

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

Simple jQuery Drop Down Menu Tutorial

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 with. 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>▼</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 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" were 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>▼</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 codes used in this tutorial for only $9.99 $5.55!
[purchase_link id="12266" text="Download Now" style="button" color="green"]

Related Tutorials

We listed all our high quality full-stack web development tutorials here: Click here.

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

jQuery UI Autocomplete Example

We, the developers, want to help our users search for the data they are looking for – in an easy manner.

This jQuery UI autocomplete tutorial will help you achieve it!

Having an autocomplete feature in our search box is really good for the user experience, it is like having a user assistant while he is trying to search.

Our code for today will make use of a textbox where the user can type his search term. The sample data we use are person names (firstname and lastname).

So, when the user types a name, our program will suggest some names that might be what the user is looking for.

Project Files

Our code for today includes the following files:

libs/db_connect.php
images/ajax-loader.gif
css/style.css
index.php
results.php

Database

The table structure used and some sample data were provided below:

--
-- Table structure for table `users`
--
 
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `gender` varchar(6) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=76 ;
 
--
-- Dumping data for table `users`
--
 
INSERT INTO `users` (`id`, `firstname`, `lastname`, `gender`, `email`, `username`, `password`, `created`, `modified`) VALUES
(49, 'Justine', 'Bongola', 'Male', '[email protected]', 'jaja', 'jaja123', '0000-00-00 00:00:00', '2013-03-03 14:06:03'),
(51, 'Lourd', 'De Veyra', 'Male', '[email protected]', 'lourd', 'lourd123', '0000-00-00 00:00:00', '2013-03-03 14:06:03'),
(73, 'Mike', 'Dalisay', '', '', 'ninjazhai', 'allisfine', '0000-00-00 00:00:00', '2013-05-12 06:39:04'),
(74, 'Darwin', 'Dalisay', '', '', 'dada', 'dada123', '0000-00-00 00:00:00', '2013-05-12 06:39:24'),
(75, 'Marykris', 'Dalisay', '', '', 'mary143', 'mary123', '0000-00-00 00:00:00', '2013-05-13 16:51:14');

Here’s how we connect to the database, just change the variable values that will make you connected to your database.

<?php
$host = "yourHost";
$db_name = "yourDatabaseName";
$username = "yourDatabaseUsername";
$password = "yourPassword";
 
try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
    echo "Connection error: " . $exception->getMessage();
}
?>

The User Interface

index.php – this is where the user can find the textbox, tries to type on it and our system suggests some keywords as autocomplete, and this is also where we include our jQuery UI theme and jQuery scripts.

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>jQuery UI auto-complete tutorial live demo</title>
 
        <!-- include the jquery ui theme css and your own css -->
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css" />
        <link rel="stylesheet" href="css/style.css" />
 
    </head>
<body>
 
<!--
    -this is our text box, we didn't use type='text' but type='search' instead
     to have a clear (x) function in case a user wants to easily remove what's in the textbox
    -placeholder='Search firstname or lastname' - is an HTML5 attribute the can give your
     users a clue on what to search or type in the textbox
-->
<div>Try to type "dalisay" below:</div>
<input type='search' id='nameSearch' placeholder='Search firstname or lastname' />
 
<!--
    -now we'll include the jQuery and jQuery UI libraries
-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
 
<script type="text/javascript">
$(document).ready(function(){
 
    // this is how to add autocomplete functionality in a textbox
    // source:'results.php' - where it will pass the search term and generates the JSON data
    // minLength:1 - how many characters user enters in order to start search
    $('#nameSearch').autocomplete({
 
        source:'results.php',
        minLength:1,
        select: function(event, ui){
 
            // just in case you want to see the ID
            var accountVal = ui.item.value;
            console.log(accountVal);
 
            // now set the label in the textbox
            var accountText = ui.item.label;
            $('#nameSearch').val(accountText);
 
            return false;
        },
        focus: function( event, ui ) {
            // this is to prevent showing an ID in the textbox instead of name
            // when the user tries to select using the up/down arrow of his keyboard
            $( "#nameSearch" ).val( ui.item.label );
            return false;
        },
 
   });
 
});
</script>
 
</body>
</html>

4.0 Getting Search Results

results.php – this is where the search term were passed, queries the database and generates the JSON data needed to show the autocomplete terms in the user interface.

<?php
// connect to the database
include "libs/db_connect.php";
 
// get the search term
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";
 
// write your query to search for data
$query = "SELECT 
            id, firstname, lastname 
        FROM 
            users 
        WHERE 
            firstname LIKE "%{$search_term}%" OR 
            lastname LIKE "%{$search_term}%"
        LIMIT 0,10";
 
$stmt = $con->prepare( $query );
$stmt->execute();
 
// get the number of records returned
$num = $stmt->rowCount();
 
if($num>0){ 
 
    // this array will become JSON later
    $data = array();
 
    // loop through the returned data
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
 
        $data[] = array(
            'label' => $firstname . " " . $lastname,
            'value' => $id
        );
    }
 
    // convert the array to JSON
    echo json_encode($data);
 
}
 
//if no records found, display nothing
else{
    die();
}
?>

Wondering how the returned JSON data looks like?

[
  {
    "label": "Mike Dalisay",
    "value": "28"
  },
  {
    "label": "Darwin Dalisay",
    "value": "40"
  }
]

You can also take a look at your own JSON data by browsing your results.php?term=your_search_term

Adding Some Styles

style.css – this is where you can change the loading GIF image and add some style to our textbox.

.ui-autocomplete-loading {
    /* you can replace ajax-loader.gif with another gif image you want for your design */
    background: white url('images/ajax-loader.gif') right center no-repeat;
}
 
/* some style for our textbox */
#nameSearch{
    padding:.5em;
    width:20em;
}

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id="12417" text="Download Now" style="button" color="green"]

Congratulations! Now you can make your users happier by this search assistant feature, and as always, thanks for reading!

Google said “The web should be fast”: How to Optimize Your Website for Speed

Hey guys! Today we have a guest post about some tips on how to speed up your website! He's currently working for an e-commerce website and one of his tasks is to make the site load fast. So enjoy reading below! ~ Mike

Website speed becomes an obsession of search engines like Google and one of the reasons is the rapid growth of mobile internet browsing. If you're working with the https://www.igloosoftware.com/product/integrations/org_chart_now/ (developers, designers, bloggers and students), it is now a requirement to have knowledge in making a website load fast, and our post for today will give you some ideas on why and how to achieve it.

MUST READ NOTE FROM GOOGLE

"Speeding up websites is important — not just to site owners, but to all Internet users. Faster sites create happy users and we've seen in our internal studies that when a site responds slowly, visitors spend less time there. But faster sites don't just improve user experience; recent data shows that improving site speed also reduces operating costs. Like us, our users place a lot of value in speed — that's why we've decided to take site speed into account in our search rankings. We use a variety of sources to determine the speed of a site relative to other sites."

WEBSITE SPEED AND PERFORMACE

Pagespeed Insights - analyzes the content of a web page, then generates suggestions to make that page faster.


Pingdom Website Speed Test - one of the most reliable website speed tester, you can test the load time of your page, analyze it and find bottlenecks.

Yslow – is also a plugin that grades website and gives statistical information of your website performance.

GTmetrix – provides result right away and suggest necessary improvement for your website

Weboptimization - analyzes and gives detailed recommendations for site improvement as well as your web page speed report.

IMAGE OPTIMIZATION

Photoshop - when saving your photo choose the option "Save as for Web and Devices" (see Mike's post here for a more detailed instruction). Compare the result of your image to its original size; see also if the visual quality changed. In my example image, this is the result of my tests.

  1. JPG, 60 quality - 32K
  2. PNG-8, 256 colors - 37K
  3. GIF, 256 colors - 42K
  4. PNG-24 - 146K

Yahoo Smush.It - "drag or paste your photo urls". It is a "lossless" tool, which means it optimizes the images without changing their look or visual quality.

Image optimizer - is also a free tool and can compress image in bulk.Tip: Crop white spaces of images and other unnecessary pixels to reduce file size of your file.

COMPRESS YOUR HTML, CSS AND JAVASCRIPT

HTMLCompressor – is a small java library that minifies codes in html and xml by removing unnecessary characters and whitespaces without changing your codes.4.2JSCompress - copy paste your javascript code and compress it online to reduce 30% to 90% unneeded characters or comments.4.3Prettydiff – Minify, beautify and compare your code online. This tool is used by W3.org and Travelocity.

MinifyCSS – has css and javascript compression tool. It helps you clean and compress codes without manipulating or installing other applications. Copy paste and submit your code online then get the same result right away.Note: If you already use gzip, you don’t need to use some of the tools recommended above.

PERFORMANCE BEST PRACTICES

Scripts

Script position - always put your JavaScripts at the end of your HTML document, usually before the ending tag. What it does is it loads the more important content of your page (like images, text, etc.) before the scripts, and that makes your page load faster.

Use external CSS instead of inline CSS.Good practice:

<link type='text/css' rel='stylesheet' href='//www.yoursite.com/styles/main.css' />

Not recommended to include in your HTML document:

<style>
.myClass{
    padding:0 .5em;
    margin:1em;
}

#myId{
    padding:.5em;
    border:thin solid red;
}
style>

or

<div style='width:20em; border:thin solid #d1d1d1;'>Some div contents here.div>

Combine Rules and use it once in CSS.Use this sample as a guide:

h1 { color: blue; }
p { color: blue; }

Combined rule:

h1, p { color: blue; }

Validate your script at  W3.Org Validator

Cache - Cache your web pages. This is very important specially to an e-commerce website and those sites that have a lot of visitors daily.

Comment Box – If you guys use comment box system, please lazy load it so that it will load only when the user reaches the lower part of your page.

CDN (content distribution/delivery network)

Some may not be familiar with Google CDN but take a moment to learn and take advantage to use the Hosted Libraries.

Cloudflare - we used this in our ecommerce site and other sites for almost 3 years and so far, we are secured and it is free of charge but they also offer advance services with fee.

Use HTML5 codes that gives you a solution for faster page performance and integrationOur HTML5 sample:

<!DOCTYPE html>

Instead of:

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Note: Some tutorials for you to learn HTML5 are my favorite sites when I was starting w3schools and in advance learning html5 rocks tutorials. 

HOSTING SERVICES

Check your Hosting Services if they provide you the best hosting solution and better web performance. You can test their website using the above tools. Shared hosting are usually the worst, especially if your website has a lot of visitors, you should have a dedicated server.Thanks guys for reading my insights, I hope you get new techniques in improving your website speed or projects. Let’s help one another to become a better designer and developer.Feel free to comment and subscribe to our tutorials.

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!
[purchase_link id="12230" text="Download Now" style="button" color="green"]

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

We listed all our high quality full-stack web development tutorials here: Click here.

8.0 Some Notes

What students say?

Don't just take our word for it. See what our students have to say about our tutorials and source codes. We are proud to have helped many individuals and businesses to build their own applications. Here are a few of the testimonials from our satisfied students.

★★★★★ “Wow, I love you guys! The best web programming tutorial I’ve ever seen. So comprehensive, yet easy to follow. I love how you combine all necessary elements in such a neat structure.” ~ Olaug Nessa

★★★★★ “The fact that you’ve put it all together saves so much time and its worth buying the code. Makes me feel good supporting a developer like yourself. Keep up the good work!” ~ Dan Hudson

★★★★★ “Thanks for making these awesome tutorials! I bought your source codes. To be honest, it’s very readable code and helps me understand a lot of things and how it’s done in PHP. Thanks for that again.” ~ Michael Lammens

★★★★★ “Hey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

★★★★★ “Words can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

Got comments?

At codeofaninja.com, we strive to provide our readers with accurate and helpful jQuery Tutorial for Beginners – Step By Step Guide! Your feedback is essential in helping us achieve this goal.

If you have encountered any issues with the code, have suggestions for improvement, or wish to provide praise, we welcome you to leave a comment below. Please be as descriptive as possible to address your concerns effectively and include any relevant error messages, screenshots, or test URLs.

We request that comments remain on-topic and relevant to the article above. If your question or comment pertains to a different topic, we recommend seeking assistance elsewhere.

Furthermore, we ask that you review our code of conduct before commenting to ensure that your feedback is constructive and respectful.

Thank you for taking the time to provide feedback and for supporting codeofaninja.com. Your contributions help us improve our tutorials and serve the developer community better.

Subscribe for FREE!

Improve your web development skills and stay ahead of the competition by subscribing to our tutorial series. Sign up for FREE and access exclusive, cutting-edge content delivered straight to your inbox.

Take advantage of the chance to elevate your skills and advance your web development career. Subscribe now.

Thank You!

We hope you've found our jQuery Tutorial for Beginners – Step By Step Guide! helpful and informative. We understand that learning new programming concepts can be challenging, but we're glad we could make it easier for you.

Thank you for choosing to learn with us and for supporting codeofaninja.com! Consider sharing this tutorial with your friends and colleagues who may also be interested in learning about jQuery Tutorial for Beginners – Step By Step Guide!

The more people know about our tutorials, the more we can help the developer community grow. Keep learning, keep coding, and keep growing as a developer. We can't wait to see what you'll create next!

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

jQuery UI Tutorial for Beginners – Step by Step Guide!

jquery-ui-tutorial-for-beginners

Previously, we learned how to use jQuery to add some interactivity to our web pages. This time, are you getting started with jQuery UI? You've come to the right place!

This step by step tutorial aims to give you a head start in using jQuery UI. You probably know what jQuery is so you want to take a beautiful step forward with jQuery UI, and that's awesome!

jQuery UI jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library.

Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is a perfect choice.

For me, Bootstrap and jQuery UI look good together. It also allows us to choose from different themes available, you can even create your own theme! But this post only covers running a very simple jQuery UI script in your web browser.

Run jQuery UI in 6 Easy Steps

The following steps below will make an awesome date picker with jQuery UI. Let's code!

Prepare your HTML file with just its basic structure.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
         
    </head>
<body>
 
</body>
</html>

Add a text box inside the tag.

Users will be able to click this and show a jQuery UI calendar picker later.

<input type="text" id="myDatepicker" placeholder="Click to pick date" />

Add the jQuery library before the ending tag.

This is because jQuery UI is built on top of the jQuery library.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Add the jQuery UI library under the code of step 3.

This is actually the first step in enabling jQuery UI on your page.

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

Add jQuery UI theme via CSS external link

Put it inside the tag, after the tag. This CSS will make our UI stylish.

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css" />

Enable jQuery UI date picker to our text box on Step 1.

Add the following code under the code of step 5. This is how you make a simple text box to an awesome jQuery UI date picker.

<script>
$( "#myDatepicker" ).datepicker();
</script>

Quick Tip: Always use the minified version. For instance, use jquery-ui.min.css instead of just jquery-ui.css

Continue to read below, you will see the complete code of the steps above.

jQuery UI Sample Codes

You will have to click the text box saying "Click to pick a date" to see jQuery UI with different themes in action.

By the way, examples 2.1 and 2.2 uses Google's content delivery network to run jQuery UI, meaning you won't have to download the jQuery and jQuery UI library, you just have to include it.


Query UI with Smoothness theme hosted in Google CDN.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - smoothness theme - by codeofaninja.com</title>
         
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css" />
         
    </head>
<body>
 
<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />
 
<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- step 3 -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>
 
</body>
</html>

jQuery UI with Vader theme hosted by Google too.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - vader theme - by codeofaninja.com</title>
         
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/vader/jquery-ui.min.css" />
         
    </head>
<body>
 
<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />
 
<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- step 3 -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>
 
</body>
</html>

What if I don't want a CDN? I want to host my own jQuery UI library? No problem, you can always go to the jQuery UI download builder, you just have to select your preferred theme using the dropdown at the lower part of the page.

jquery ui download builder

jQuery UI library is self-hosted in the example code below.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - vader theme - by codeofaninja.com</title>
         
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="jquery-ui-1.10.3.custom/css/le-frog/jquery-ui-1.10.3.custom.min.css" />
         
    </head>
<body>
 
<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />
 
<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- step 3 -->
<script src="jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>
 
<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>
 
</body>
</html>

Download Source Code

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

[purchase_link id="12401" text="Download Now" style="button" color="green"]

Online Resources

Want to see more of jQuery UI? You can always visit:

What's Next?

Up Next: Learn PHP and MySQL CRUD Tutorial for Beginners - Build a simple web application with PHP and MySQL database.

Related Tutorials

We listed all our high quality full-stack web development tutorials here: Click here.

Some Notes

What students say?

Don't just take our word for it. See what our students have to say about our tutorials and source codes. We are proud to have helped many individuals and businesses to build their own applications. Here are a few of the testimonials from our satisfied students.

★★★★★ “Wow, I love you guys! The best web programming tutorial I’ve ever seen. So comprehensive, yet easy to follow. I love how you combine all necessary elements in such a neat structure.” ~ Olaug Nessa

★★★★★ “The fact that you’ve put it all together saves so much time and its worth buying the code. Makes me feel good supporting a developer like yourself. Keep up the good work!” ~ Dan Hudson

★★★★★ “Thanks for making these awesome tutorials! I bought your source codes. To be honest, it’s very readable code and helps me understand a lot of things and how it’s done in PHP. Thanks for that again.” ~ Michael Lammens

★★★★★ “Hey Mike, my name is Leonardo from Argentina. I’ve been reading your blog since like 4 months from now, and I really must say: your tutorials are very good, they has helped me in many of my works… Well, thank you very much man. I really admire your work.” ~ Leonardo

★★★★★ “Words can’t express how grateful I am for the work and the articles you post, had some troubles with doing somethings but your articles as per usual hit the hammer right on the head. They are a great way for expanding upon later too!” ~ Jeremy Smith

Got comments?

At codeofaninja.com, we strive to provide our readers with accurate and helpful jQuery UI Tutorial for Beginners – Step by Step Guide! Your feedback is essential in helping us achieve this goal.

If you have encountered any issues with the code, have suggestions for improvement, or wish to provide praise, we welcome you to leave a comment below. Please be as descriptive as possible to address your concerns effectively and include any relevant error messages, screenshots, or test URLs.

We request that comments remain on-topic and relevant to the article above. If your question or comment pertains to a different topic, we recommend seeking assistance elsewhere.

Furthermore, we ask that you review our code of conduct before commenting to ensure that your feedback is constructive and respectful.

Thank you for taking the time to provide feedback and for supporting codeofaninja.com. Your contributions help us improve our tutorials and serve the developer community better.

Subscribe for FREE!

Improve your web development skills and stay ahead of the competition by subscribing to our tutorial series. Sign up for FREE and access exclusive, cutting-edge content delivered straight to your inbox.

Take advantage of the chance to elevate your skills and advance your web development career. Subscribe now.

Thank You!

We hope you've found our jQuery UI Tutorial for Beginners – Step by Step Guide! helpful and informative. We understand that learning new programming concepts can be challenging, but we're glad we could make it easier for you.

Thank you for choosing to learn with us and for supporting codeofaninja.com! Consider sharing this tutorial with your friends and colleagues who may also be interested in learning about jQuery UI Tutorial for Beginners – Step by Step Guide!

The more people know about our tutorials, the more we can help the developer community grow. Keep learning, keep coding, and keep growing as a developer. We can't wait to see what you'll create next!

Thanks for reading our jQuery UI tutorial for beginners!

jQuery UI Dialog Example with Source Code Downloads

Dialog boxes, modals, confirm boxes can also be done with awesomeness in jQuery UI.

In this post we are going to take a look at the three jQuery UI dialog code examples I commonly use in my projects.

Live demos and code download button links were also provided below. Keep on reading!

jquery ui dialog example

Our jQuery, jQuery UI and jQuery UI theme are hosted by Google. You can choose your jQuery UI theme here.

jQuery UI Basic Modal

I love modals, or a "modal window" or "modal dialog", it is a child window that pops up in your application that requires a user interaction. It can display information, gives you choices or even contain an HTML form!

In jQuery UI, when you set modal: true parameter, it will be able to dim the background of your page when showing the dialog. If it is set to false, the background will remain as is.

This is useful when a client (like mine) did not like dimming the background. But I like dimming the background when showing a dialog, so in our code below, we'll set the modal to true.

basic-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Modal Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />
 
<!-- 
    -this is the actual dialog, yes, it is included in your html body, it is just hidden
    -you can set the dialog title via the 'title' tag 
-->
<div id="basicModal" title="A message from codeofaninja.com">
    Thank you for visiting codeofaninja.com!
</div>
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* -select the div you want to be a dialog modal, in our case it is 'basicModal'
       -you can add parameters such as width, height, title, etc. */
    $( "#basicModal" ).dialog({
        modal: true,
        height: 300,
        width: 400
    });
     
});
</script>
 
</body>
</html>

jQuery UI Confirm Dialog

Instead of the old JavaScript confirm dialog box, I use jQuery UI. This is for a better user interface and to control the number of buttons and their labels, instead of just "ok" and "cancel".

confirm-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Confirm Dialog Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show confirm dialog!' id='showDialog' />
 
<!-- 
    -this is the actual dialog, yes, it is included in your html body, it is just hidden
    -we did not set the dialog 'title' here, we set it in the js parameter
-->
<div id="basicModal">
    Go to codeofaninja.com?
</div>
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* select the div you want to be a dialog, in our case it is 'basicModal'
    you can add parameters such as width, height, title, etc. */
    $( "#basicModal" ).dialog({
        modal: true,
        title: "Are you sure?",
        buttons: {
            "YES": function() {
                window.open("https://codeofaninja.com/", '_blank');
            },
            "NO": function() {
                $( this ).dialog( "close" );
            }
        }
    });
     
});
</script>
 
</body>
</html>

jQuery UI Load Content from URL

URL to be loaded must be in the same domain or subdomain name. If you really want to load from different domain, use iframes, example code here.

In this example, we will use sample_page.php as the file of URL to be loaded, it has the following contents:

<?php
echo "Here's the sample page loaded.<br /><br />";
echo "Only a page from the same domain/subdomain can be loaded using this technique.<br /><br />";
echo "If you really want to load a page from another domain/subdomain, use an iframe.<br /><br />";
echo "<a href='http://stackoverflow.com/a/14570255/903298' target='_blank'>Example code here</a>";
?>

Save the loaded URL content

Here's is the default behaviour of the jQuery UI dialog, it appends the URL content to the HTML body.

load-url-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />
 
<!-- 
    -this time, we don't have the dialog html in the body, it is in another url
    -we use the image loader to add some good effect when the system loads the url (after user click)
 -->
<img src="images/ajax-loader.gif" id="imgLoader" style="display:none;" />
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* here you can specify the url */
    var url = "sample-page.php";
     
    /* container of the content loaded from a url */
    var tag = $("<div></div>");
     
    console.log("url: " + url);
     
    /* show the image loader */
    $('#imgLoader').show();
     
    $.ajax({
        url: url,
        success: function( data ) {
         
            tag.html(data).dialog({
                modal: true,
                title: "Content is loaded from a URL!",
                width: 600,
                height: 450
            }).dialog('open');
 
            /* hide the image loader */
            $('#imgLoader').hide();
            console.log("success!");
        }
    });
     
});
</script>
 
</body>
</html>

To prove that the URL contents will be appended in the body of your HTML document, see the screenshot below, I used Google Chrome's inspect element to view this live source code of the current page.

jquery ui dialog not destroyed or removed

LIVE DEMO

Destroy or remove the loaded URL content

By default, the jQuery UI append the URL contents in your HTML body, if you want to prevent it, we can we add the close parameter on the dialog and use the jQuery remove() method.

load-url-destroy-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
         
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />
 
<!-- 
    -this time, we don't have the dialog html in the body, it is in another url
    -we use the image loader to add some good effect when the system loads the url (after user click)
-->
<img src="images/ajax-loader.gif" id="imgLoader" style="display:none;" />
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* here you can specify the url */
    var url = "sample-page.php";
     
    /* container of the content loaded from a url */
    var tag = $("<div></div>");
     
    /* show the image loader */
    $('#imgLoader').show();
     
    $.ajax({
        url: url,
        success: function( data ) {
         
            tag.html(data).dialog({
                modal: true,
                title: "Content is loaded from a URL!",
                width: 600,
                height: 450,
                close: function(){
                     tag.dialog('destroy').remove()
                }
            }).dialog('open');
 
            /* hide the image loader */
            $('#imgLoader').hide();
            console.log("success!");
        }
    });
     
});
</script>
 
</body>
</html>

To prove that the URL content did not append in the HTML body, see the screenshot of the live source code below.

jquery ui dialog was destroyed and removed

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id="12411" text="Download Now" style="button" color="green"]

If you think of any other jQuery UI dialog example, please drop it in the comments section below, we'll try our best to add it in this post. Thanks!

JavaScript POST request example

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

This post will show you JavaScript POST request examples. This is useful if you want to submit a form using HTML and JavaScript.

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 on 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 a 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 examples 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 on 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!
[purchase_link id="12253" text="Download Now" style="button" color="green"]

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

We listed all our high quality full-stack web development tutorials here: 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!