Working with Geolocation watchPosition() API

I’m going to share a Geolocation watchPosition() API example. This 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!

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

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.

Sum textbox values using JavaScript

A friend asked me how to sum textbox values using JavaScript? He wants to do this 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!
[purchase_link id="12278" 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 Sum TextBox Values As You Type in 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

Video Demo

Our final output.

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:

Retrieve the Records

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 ***** 
}

First and Previous Page Buttons

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>";
     
}
?>

Number Page Buttons

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> ";
        }
    }
}
 
?>

Next and Last Page Buttons

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>";
}
?>

Enter a Page Number

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>"; 
?>

Download Source Code Examples

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

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!

Scroll to top of page in JavaScript

Today I'll show you how to scroll to top of page in JavaScript. There are some friends who asked me how I did this "back to top" feature of our blog.

Imagine you 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 makes use of a long vertical scroll bar. The user can instantly go to the top of the page easily, just with one click! So here's the HTML, CSS, and JavaScript 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!

Two Example Usage of jQuery On() Method

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

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

"Home

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

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

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

Loading Different Forms to a DIV

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

form_w_on.php code:

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

add_user.php code:

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

add_role.php code:

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

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

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

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

Loading Table List to a DIV

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

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

index.php code:

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

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

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

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

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

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

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

Related Tutorials

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

A Quick Way To Create A Vertical Accordion With jQuery

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

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

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

A Quick Way To Create A Vertical Accordion With jQuery

So in this example code, we will have:

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

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

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

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

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

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

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

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

Related Tutorials

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

Dependent Drop Down List Using JavaScript

This tutorial will teach you how to make a dynamic and dependent drop down list using JavaScript. We are using PHP and MySQL as well.

Example #1

Create index.php

Create index.php with the following Basic HTML Code

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Dropdown Example</title>
</head>
<body>
 
</body>
</html>

Retrieve 'Teams' from database

Put the following code between the 'body' tags of the previous section.

<?php 
// retrieve teams from the database 
// include database and object files
include_once 'config/database.php';
include_once 'objects/team.php';
 
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
 
$team = new Team($db);
 
$stmt = $team->read();
$num = $stmt->rowCount();
 
if($num>0){
    echo "<select id='teams-dropdown'>";
    echo "<option value='0'>Select team...</option>";
    while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
        echo "<option value='{$id}'>{$name}</option>";
    }
    echo "</select>";
}
?>

Create database.php

Create database.php file. The previous section will not work without the database connection. Put the following code.

<?php
class Database{
 
    // specify your own database credentials
    private $host = "localhost";
    private $db_name = "nba";
    private $username = "root";
    private $password = "";
    public $conn;
 
    // get the database connection
    public function getConnection(){
 
        $this->conn = null;
 
        try{
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
        }catch(PDOException $exception){
            echo "Connection error: " . $exception->getMessage();
        }
 
        return $this->conn;
    }
}
?>

Create team.php

Create 'objects' folder and inside it, create team.php file. The section before the previous section will not work without this. Put the following code inside it.

<?php
class Team{
 
    // database connection and table name
    private $conn;
    private $table_name = "teams";
 
    // object properties
    public $id;
    public $name;
 
    public function __construct($db){
        $this->conn = $db;
    }
     
    // read products
    public function read(){
 
        $query = "SELECT id, name
                FROM " . $this->table_name . "
                ORDER BY name";
 
        // prepare query statement
        $stmt = $this->conn->prepare($query);
 
        // execute query
        $stmt->execute();
 
        return $stmt;
    }
     
}
?>

Create empty select box

Open index.php and put the following code under the code in section 2.0 above.

<!-- create empty select box -->
<select id='players-dropdown'>
    <option value='0'>Select player...</option>
</select>

Prepare jQuery script

Include the jQuery library and its initial script. Put the following code under the code of the previous section.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
 
});
</script>

Detect change of 'teams' dropdown

We have to detect when the user selects a team. Put the following code under "$(document).ready(function(){" of the previous section.

// detect change of dropdown
$("#teams-dropdown").change(function(){
     
    // get id of selected team 
    var team_id=$(this).find(':selected').val();
     
});

Get JSON data

Now, we will have to get the list of players based on selected team. Put the following code under "var team_id" line of code of the previous section.

// set json url
var json_url="players_json.php?team_id=" + team_id;
 
// get json data
jQuery.getJSON(json_url, function(data){
     
});

Create players_json.php

Create players_json.php file. This file will render the list of players based on selected team. We are going to use the 'JSON' data format because JavaScript can read this format easily. Put the following code inside this file.

<?php 
// set json headers
header("Access-Control-Allow-Methods: GET");
header('Content-Type: application/json');
 
// retrieve players from the database 
// get team id parameter
$team_id=isset($_GET['team_id']) ? $_GET['team_id'] : die('Team ID not found.');
 
// include database and object files
include_once 'config/database.php';
include_once 'objects/player.php';
 
// instantiate database and product object
$database = new Database();
$db = $database->getConnection();
 
$player = new Player($db);
 
$player->team_id=$team_id;
$stmt = $player->read();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
 
echo json_encode($results);
?>

Create player.php file

Go inside the 'objects' folder and create the player.php file. This file will retrieve players data from the database. Put the following code inside it.

<?php
class Player{
 
    // database connection and table name
    private $conn;
    private $table_name = "players";
 
    // object properties
    public $id;
    public $team_id;
    public $name;
 
    public function __construct($db){
        $this->conn = $db;
    }
     
    // read products
    public function read(){
 
        $query = "SELECT id, team_id, name 
                FROM " . $this->table_name . "
                WHERE team_id=:team_id
                ORDER BY name";
 
        // prepare query statement
        $stmt = $this->conn->prepare($query);
 
        // santize
        $this->team_id=htmlspecialchars(strip_tags($this->team_id));
         
        // bind value 
        $stmt->bindParam(":team_id", $this->team_id);
         
        // execute query
        $stmt->execute();
 
        return $stmt;
    }
     
}
?>

Change players dropdown

Now we will try to change the content of 'players' drop down. Open your index.php file and put the following code after "jQuery.getJSON(json_url, function(data){" line of index.php file.

// empty contents of players dropdown
$("#players-dropdown").html("");
$("#players-dropdown").append("<option value='0'>Select player...</option>");
 
// put new dropdown values to players dropdown
jQuery.each(data, function(key, val){
    $("#players-dropdown").append("<option value='" + val.id + "'>" + val.name + "</option>")
});

Example #2

I used this code when I have a small list of records (e.g. authors or categories) that can be picked using a drop-down list and then, I want to load the related information instantly without refreshing the page.

So in this post, we are going to code that does:

  • A drop down list with small number of names or authors
  • When a user selected an item from the drop down, it will load the related data below it.

We are going to use 4 files only, see below:

jQuery CDN

Prepare our favorite JavaScript library.

db_connect.php

We will use this file for database connection.

<?php
$host = "YOUR_DATABASE_HOST";
$db_name = "YOUR_DATABASE_NAME";
$username = "YOUR_DATABASE_USERNAME";
$password = "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();
}
?>

Here's the database table we used. Run the following SQL query on your PhpMyAdmin.

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
 
--
-- Dumping data for table `users`
--
 
INSERT INTO `users` (`id`, `firstname`, `lastname`, `username`, `password`) VALUES
(1, 'John', 'Doe', 'johnny', 'john'),
(2, 'Albert', 'Minston', 'albert', 'albert');

index.php

This will show the users drop-down list, records are from the database users table.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Example #2 - Dynamic and Dependent Drop Down List Using AJAX</title>
        <style>
        body{
            font-family:arial,sans-serif;
        }
 
        select{
            margin:0 0 10px 0;
            padding:10px;
        }
 
        td {
            background-color:#e8edff;
            padding: 10px;
        }
        </style>
    </head>
<body>
 
<?php
// connect to database
include_once "db_connect.php";
 
// retrieve list of users and put it in the select box
$query = "SELECT id, firstname, lastname, username FROM users";
$stmt = $con->prepare($query);
$stmt->execute();
 
//this is how to get number of rows returned
$num = $stmt->rowCount();
 
// make sure there are records on the database
if($num > 0){
 
// this will create selec box / dropdown list with user records
echo "<select id='users'>";
 
    // make a default selection
    echo "<option value='0'>Select a user...</option>";
 
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
        echo "<option value='{$id}'>{$firstname} {$lastname}</option>";
    }
echo "</select>";
 
}
 
// if no user records
else{
    echo "<div>No records found</div>";
}
 
// this is where the related info will be loaded
echo "<div id='userInfo'></div>";
?>
 
<script src="js/jquery-1.9.1.min.js" ></script>
<script>
$(document).ready(function(){
    $("#users").change(function(){
 
        // get the selected user's id
        var id = $(this).find(":selected").val();
 
        // load it in the userInfo div above
        $('#userInfo').load('data.php?id=' + id);
 
    });
});
</script>
 
</body>
</html>

data.php

This contains the query and will show the table with information related to the selected drop-down item.

<?php
include 'db_connect.php';
 
try {
 
    // prepare query
    $query = "SELECT firstname, lastname, username
            FROM users
            WHERE id = ?";
 
    $stmt = $con->prepare( $query );
 
    // this is the first question mark above
    $stmt->bindParam(1, $_REQUEST['id']);
 
    // execute our query
    $stmt->execute();
 
    // store retrieved row to a variable
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
 
    // values to fill up our table
    $firstname = $row['firstname'];
    $lastname = $row['lastname'];
    $username = $row['username'];
 
    // our table
    echo "<table>";
        echo "<tr>";
            echo "<td>Firstname: </td>";
            echo "<td>{$firstname}</td>";
        echo "</tr>";
        echo "<tr>";
            echo "<td>Lastname: </td>";
            echo "<td>{$lastname}</td>";
        echo "</tr>";
        echo "<tr>";
            echo "<td>Username: </td>";
            echo "<td>{$username}</td>";
        echo "</tr>";
    echo "</table>";
 
}catch(PDOException $exception){
 
    // to handle error
    echo "Error: " . $exception->getMessage();
}
?>

Download Source Code

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

Thank you for learning from our post about: Dynamic and Dependent Drop Down Menu with PHP, MySQL and 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>[email protected]</td>
        <td>dalisay</td>
        <td>
            <!-- It is important to understand our "Options" HTML structure. -->
            <a href="">Edit</a> /
            <a href="">Delete</a> /
            <a href="" class="moreOptionsLink">More</a>

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

jQuery code – the animation and magic. :)

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

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

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

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

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

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

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

Codes combined:

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

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

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

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

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

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

    .verticalOption{
        margin:8px 0;
    }

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

    .moreOptionsLink:hover{
        color:#fff;
    }

    .moreOptions{
        display:none;
    }

    </style>
</head>
<body>

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

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

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

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

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

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

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

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

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

</body>
</html>

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id="12285" 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 jQuery slideToggle Example - Solution Row's Long List of Options!