Posts

Home Lists+

12 jQuery Questions and Answers You Should Be Reading on StackOverflow

Hi guys! Below are twelve of the jQuery related questions and answers on StackOverflow that I found very useful during development. I opted to compile them here because I feel good reading those brilliant questions and answers by coders from around the world. Enjoy!

  1. How would I know if an element is hidden?
  2. Sometimes you want some elements of your page to be visible, and if it is not visible, you want to tell the user about it. For example, a user must have a selection of data first before proceeding to new operation. If he has no selection (div is hidden), you can do a prompt that he must select something.

  3. How do I get selected text in select box?
  4. Ah, a drop-down list? Link # 2 above shows you how to get the user drop down list selection.

  5. How to redirect a page?
  6. Useful if you want to your users to see a page after an AJAX request, or you just want them to be redirected. I’ve written another example here, jQuery: Redirect onClick

  7. How would I know if a checkbox is checked or unchecked?
  8. For example, you want to enable a delete button if the user selected at least one data to delete, else, the delete button is disabled. I’ve written another example here: Check or Uncheck Checkboxes with jQuery And Get Selected with PHP

  9. How to select a child element?
  10. Teaches us how to select a child element and do it with faster performance (see the comment by Paul Irish).

  11. event.preventDefault() vs. return false
  12. I use return false; when I want to prevent a page refresh after clicking a submit button and doing an AJAX request.

  13. Example of using jQuery .closest() method.
  14. I use jQuery .closest() method on selecting an element within a table with several rows. I probably have to write an example in another blog post, ha!

  15. How would I know the existence of an element?
  16. Useful if you want to perform something if an element exists in your page. The faster way is using if ($(selector).length) {}

  17. How would I know which radio button is selected?
  18. This is how you will know if a user is a male or female, using jQuery!

  19. How to select multiple classes?
  20. Sometimes you want to to something to multiple classes at once. There’s another example here.

  21. How to select an element by its name, not by class or id?
  22. If you’re more familiar with an element’s name or don’t want to add a class or id name, you can use this cool technique.

  23. What if Google hosted jQuery is blocked?
  24. In some countries, Google’s domain name is banned. So if you are using a Google hosted jQuery library, you’re site won’t work. Link # 12 above shows you the fall back.

This can be the first part of the list, you can add more in the comments section below, or on our Facebook, Twitter or Google+!
And as always, thanks for reading!

Home jQuery

Working with Geolocation watchPosition() API

I’m going to share a working navigator.geolocation.watchPosition() code I used when I wanted the user to know his current location in real time (while he is walking or riding a vehicle).

This works while the user is using his Android device or any device with a browser that supports the Geolocation API.

We made this code with the help of Google Maps and jQuery.

Working with Geolocation watchPosition() API

Live Demo

Recommended to use a mobile device, you must allow it to get your current location, don’t worry, I’m not tracking you.

Code Example

Now here’s our index.html code.

<!DOCTYPE HTML>
<html>
<head>
    <title>Geolocation watchPosition() by The Code of a Ninja</title>
    
    <!-- for mobile view -->
    <meta content='width=device-width, initial-scale=1' name='viewport'/>
    
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"></script>
    <script type="text/javascript">

        // you can specify the default lat long
        var map,
            currentPositionMarker,
            mapCenter = new google.maps.LatLng(14.668626, 121.24295),
            map;

        // change the zoom if you want
        function initializeMap()
        {
            map = new google.maps.Map(document.getElementById('map_canvas'), {
               zoom: 18,
               center: mapCenter,
               mapTypeId: google.maps.MapTypeId.ROADMAP
             });
        }

        function locError(error) {
            // tell the user if the current position could not be located
            alert("The current position could not be found!");
        }

        // current position of the user
        function setCurrentPosition(pos) {
            currentPositionMarker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(
                    pos.coords.latitude,
                    pos.coords.longitude
                ),
                title: "Current Position"
            });
            map.panTo(new google.maps.LatLng(
                    pos.coords.latitude,
                    pos.coords.longitude
                ));
        }

        function displayAndWatch(position) {
        
            // set current position
            setCurrentPosition(position);
            
            // watch position
            watchCurrentPosition();
        }

        function watchCurrentPosition() {
            var positionTimer = navigator.geolocation.watchPosition(
                function (position) {
                    setMarkerPosition(
                        currentPositionMarker,
                        position
                    );
                });
        }

        function setMarkerPosition(marker, position) {
            marker.setPosition(
                new google.maps.LatLng(
                    position.coords.latitude,
                    position.coords.longitude)
            );
        }

        function initLocationProcedure() {
            initializeMap();
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
            } else {
                // tell the user if a browser doesn't support this amazing API
                alert("Your browser does not support the Geolocation API!");
            }
        }

        // initialize with a little help of jQuery
        $(document).ready(function() {
            initLocationProcedure();
        });
    </script>
</head>

<body style="margin:0; padding:0;">
    
    <!-- display the map here, you can changed the height or style -->
    <div id="map_canvas" style="height:25em; margin:0; padding:0;"></div>
</body>

</html>

In my case, I used this code with an Android WebView since it should be seen inside an app I’m working on, but as I said, this will work with any device with a browser.

If you have the same case as mine, you can also use this piece of android WebView code.

Just add:

webSettings.setGeolocationEnabled(true);

and inside your setWebChromeClient()…

@Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
    
    super.onGeolocationPermissionsShowPrompt(origin, callback);
    callback.invoke(origin, true, false);
}

Download Source Code

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

Issues Encountered

If you were testing it with an Adroid Webview or Chrome Browser and seemed like it is not working, don’t lose hope. There is always hope. :)

Here’s the solution, uninstall the Chrome browser and then re-install it.

Related Source Code

Google Maps Geocoding Example with PHP - This tutorial is about a Google Maps geocoding example with PHP. We used some Google Maps JavaScript to show the geo-coded data on the map as well.

Further Reading

Geolocation API Specification
Geolocation.watchPosition() from Mozilla Developer Network

Don’t hesitate to post your comments regarding this Geolocation watchPosition() API example code.

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 Lists+

CSS3 Rotate Image On Hover

Have you seen our logo on the upper left corner? Try to hover on it, it will rotate 360 degrees. Looks cool? In this quick post, I’m going to show you how I did that using CSS3.

CSS:

#linkWrapRotator img {
     -webkit-transition: all 1s ease-in-out;
     -moz-transition: all 1s ease-in-out; 
     -o-transition: all 1s ease-in-out; 
     -ms-transition: all 1s ease-in-out; 
}

#linkWrapRotator img:hover { 
     -webkit-transform: rotate(360deg); 
     -moz-transform: rotate(360deg); 
     -o-transform: rotate(360deg);
     -ms-transform: rotate(360deg); 
}

HTML used:

<a href='https://www.codeofaninja.com/' id='linkWrapRotator'>
     <img src='https://lh6.googleusercontent.com/-Q0p2PeGBLLg/UTr5zOvggSI/AAAAAAAAEeM/SrYuO-cYWQU/s205/ninja-icon200x200.png' />
</a>

You can also do the rotation in other degrees, not on 360, just change the value of “rotate” in our code. For example, you can do rotate(180deg);

Just play with it!

Now that was fast and easy, I know there are other ways to do it, like using jQuery. There would also be some variations in doing this, such as not having a "a" tag.

Please share your own beautiful work, experience and cases on the comment section below!

Home jQuery

Simple PHP Pagination Script to Handle Your Growing Data

PHP Pagination is another very important feature when building any web application.

When you grow your data, it must not be displayed on a single page – it can cause a browser hang or very long vertical scroll-bar, so in short, it is not good for the user experience.

Simple PHP Pagination Script to Handle Your Growing Data

Contents:
1.0 Video Demo
2.0 Pagination in 5 Easy Steps
2.1 Retrieving the Records
2.2 First and Previous Page
2.3 Number Page Buttons
2.4 Next and Last Page Buttons
2.5 User Input Page Number
3.0 Download Source Code

1.0 Video Demo

Our final output.

2.0 Pagination in 5 Easy Steps

We are going the build this PHP paging script, in just 5 easy steps, see 3.1 to 3.5 below:

2.1 Retrieve the Records (Step 1)

This code will connect us to a MySQL database. Create "libs" folder. Open that folder. Create "db_connect.php" file and place the following code.

<?php
$host = "CHANGE_TO_YOUR_HOST";
$db_name = "CHANGE_TO_YOUR_DATABASE_NAME";
$username = "CHANGE_TO_YOUR_DATABASE_USERNAME";
$password = "CHANGE_TO_YOUR_DATABASE_PASSWORD";

try {
	$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}

//to handle connection error
catch(PDOException $exception){
	echo "Connection error: " . $exception->getMessage();
}
?>

Next, we will show the records in an HTML table.

<?php
// include for database connection
include 'libs/db_connect.php';

// page is the current page, if there's nothing set, default is page 1
$page = isset($_GET['page']) ? $_GET['page'] : 1;

// set records or rows of data per page
$recordsPerPage = 3;

// calculate for the query LIMIT clause
$fromRecordNum = ($recordsPerPage * $page) - $recordsPerPage;

// select all data
$query = "SELECT 
            id, firstname, lastname, username 
        FROM 
            users 
        ORDER BY 
            id desc
        LIMIT 
            {$fromRecordNum}, {$recordsPerPage}";
            
            /*
            page and its LIMIT clause looks like:
            1 = 0, 5
            2 = 5,10
            3 = 10,15
            4 = 15, 20
            5 = 20, 25
            */
        
$stmt = $con->prepare( $query );
$stmt->execute();

//this is how to get number of rows returned
$num = $stmt->rowCount();

//check if more than 0 record found
if($num>0){

    //start table
    echo "<table id='tfhover' class='tftable' border='1'>";
    
        //creating our table heading
        echo "<tr>";
            echo "<th>Firstname</th>";
            echo "<th>Lastname</th>";
            echo "<th>Username</th>";
        echo "</tr>";
        
        //retrieve our table contents
        //fetch() is faster than fetchAll()
        //http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        
            //extract row, this will make $row['firstname'] to just $firstname only
            extract($row);
            
            //creating new table row per record
            echo "<tr>";
                echo "<td>{$firstname}</td>";
                echo "<td>{$lastname}</td>";
                echo "<td>{$username}</td>";
            echo "</tr>";
        }
        
    echo "</table>";//end table

    // ***** Paging section will be here ***** 
}

2.2 First and Previous Page Buttons (Step 2)

The code below will show the "First" and "Previous" page buttons.

// ***** for 'first' and 'previous' pages
if($page>1){
    // ********** show the first page
    echo "<a href='" . $_SERVER['PHP_SELF'] . "' title='Go to the first page.' class='customBtn'>";
        echo "<span style='margin:0 .5em;'> << </span>";
    echo "</a>";
    
    // ********** show the previous page
    $prev_page = $page - 1;
    echo "<a href='" . $_SERVER['PHP_SELF'] 
            . "?page={$prev_page}' title='Previous page is {$prev_page}.' class='customBtn'>";
        echo "<span style='margin:0 .5em;'> < </span>";
    echo "</a>";
    
}
?>

2.3 Number Page Buttons (Step 3)

We are going to have some simple calculations here. The goal of this code is to display some page numbers that users can click.

<?php
// ********** show the number paging

// find out total pages
$query = "SELECT COUNT(*) as total_rows FROM users";
$stmt = $con->prepare( $query );
$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total_rows = $row['total_rows'];

$total_pages = ceil($total_rows / $recordsPerPage);

// range of num links to show
$range = 2;

// display links to 'range of pages' around 'current page'
$initial_num = $page - $range;
$condition_limit_num = ($page + $range)  + 1;

for ($x=$initial_num; $x<$condition_limit_num; $x++) {
    
    // be sure '$x is greater than 0' AND 'less than or equal to the $total_pages'
    if (($x > 0) && ($x <= $total_pages)) {
    
        // current page
        if ($x == $page) {
            echo "<span class='customBtn' style='background:red;'>$x</span>";
        } 
        
        // not current page
        else {
            echo " <a href='{$_SERVER['PHP_SELF']}?page=$x' class='customBtn'>$x</a> ";
        }
    }
}

?>

2.4 Next and Last Page Buttons (Step 4)

This will show the buttons with characters “>” and “>>” (meaning ‘next’ and ‘last’)

<?php
// ***** for 'next' and 'last' pages
if($page<$total_pages){
    // ********** show the next page
    $next_page = $page + 1;
    echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$next_page}' title='Next page is {$next_page}.' class='customBtn'>";
        echo "<span style='margin:0 .5em;'> > </span>";
    echo "</a>";
    
    // ********** show the last page
    echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$total_pages}' title='Last page is {$total_pages}.' class='customBtn'>";
        echo "<span style='margin:0 .5em;'> >> </span>";
    echo "</a>";
}
?>

2.5 Enter a Page Number (Step 5)

This will show a text-box where the user can enter a page number and submit it by hitting the enter key or clicking the ‘Go’ button.

<?php
// ***** allow user to enter page number
echo "<form action='" . $_SERVER['PHP_SELF'] . "' method='GET'>";
    echo "Go to page: ";
    echo "<input type='text' name='page' size='1' />";
    echo "<input type='submit' value='Go' class='customBtn' />";
echo "</form>"; 
?>

3.0 Download Source Code Examples

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

If you want to paginate with jQuery, here’s a post I made: Pagination with jQuery and PHP

Thank you for learning from our post about: Simple PHP Pagination Script!

Home jQuery

Scroll Page to Top Using jQuery

There are some friends who asked me how I did this "back to top" feature of our blog. For a live demo, try to scroll down this page, you will see an "up arrow" image on the lower right corner. When you click it, it will get you to the top of this page.

Code of a Ninja Scroll Page To Top

For me this is another cool feature for any website that make use of long vertical scroll bar. The user can instantly go the the top of the page easily, just in one click! So here's the HTML, CSS and jQuery code I used:

HTML - this will make our 'up arrow' image shown.

<a href="#" class="ninjaUp" title='Back to top...'>Scroll</a>

CSS - our arrow image looks a little blurred, but when you hover your mouse on it, it will be emphasized, thanks to CSS opacity!

.ninjaUp{
width:128px;
height:128px;
opacity:0.3;
position:fixed;
bottom:10px;
right:10px;
display:none;
text-indent:-9999px;
background: url('https://lh6.googleusercontent.com/-jqrSBwq8jN8/UYSas7Y9_eI/AAAAAAAAFGA/AESC5Kc64-I/s128/1367662569_upload_arrow_up.png') no-repeat;
}

.ninjaUp:hover{
opacity:0.6;
}

jQuery - this will detect scrolling, do the fade effect and scroll to top animation!

<script type="text/javascript">
$(document).ready(function(){

// detect scroll
$(window).scroll(function(){

// if the user scrolled the page more that 200 pixels, show the 'up' arrow image
if ($(this).scrollTop() > 200) {
$('.ninjaUp').fadeIn();
}

// hide the 'up' arrow image
else {
$('.ninjaUp').fadeOut();
}

});

// when the user clicks on the 'up' arrow image, it will scroll the page to the top
// it will occur in a second (see 1000 value below)
// you can change that value if you want to make the scroll faster or slower
$('.ninjaUp').click(function(){
$("html, body").animate({ scrollTop: 0}, 1000);
return false;
});

});
</script>

How about if I don't what to "scroll" it. Easy, you just have to make value to "0", so the code will be like this:

$('.ninjaUp').click(function(){
$("html, body").animate({ scrollTop: 0}, 0);
return false;
});

It is beautiful! Thanks to jQuery functions like jQuery scroll and animate and CSS Opacity!

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