Posts

Home jQuery

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

Read more

Home jQuery

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.

Read more

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.

Contents of this tutorial include:
1.0 Getting Started with jQuery
2.0 Run jQuery in 5 Easy Steps
3.0 Download Source Code
4.0 jQuery Basic Concepts
5.0 Online Resources
6.0 What's Next?
7.0 Related Tutorials
8.0 Some Notes

1.0 Getting Started with jQuery

1.1 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.

1.2 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)

2.0 Run jQuery in 5 Easy Steps

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

Step 1: Create HTML page with its basic structure.

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

</body>
</html>

Step 2: 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>

Step 3: 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>

Step 4: 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>

3.0 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.

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

4.2 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

4.3 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

4.4 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

8.0 Some Notes

#1 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.

#2 Become a true Ninja!

We constantly add new tutorials and improve our existing tutorials and source codes. Be one of the first to know an update by subscribing to our FREE newsletter. CLICK HERE TO SUBSCRIBE FOR FREE!

#3 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.

Home jQuery

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!

1. 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>

2. 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>

3. 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

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!

Home jQuery

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

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

Home 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>jQuery Two Example Usage of jQuery On() Method

Loading and submitting a from without page refresh.

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

Home jQuery

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

Home jQuery

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>jm@gmail.com</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>jm@gmail.com</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>edward_cullen@yahoo.com</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>vane@yahoo.com</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>mike@gmail.com</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

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