Posts

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

Dynamic and Dependent Drop Down List Using AJAX

This tutorial will teach you how to make Dynamic and Dependent Drop Down List using AJAX.

We are using PHP and MySQL as well.

Example #1

1.0 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>

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

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

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

5.0 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>

6.0 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>

7.0 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();
	
});

8.0 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){
	
});

9.0 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);
?>

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

11.0 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:

1.0 jQuery CDN

Prepare our favorite JavaScript library.

2.0 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');

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

4.0 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!

Thank you for learning from our post about: Dynamic and Dependent Drop Down Menu with PHP, MySQL and jQuery!

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!

Home Lists+

How To Make Responsive Web Design CSS Code?

In today’s tutorial, I’m going to show you a systematic and very simple way to create a responsive website with CSS3 media queries and HTML5.

Responsive web design has been around for few years now and is widely accepted as a new standard when building a modern website.

Coding A Responsive Website Design

For the “live demo”, please try to resize your browser to see the page’s responsiveness.

I want to give you a brief definition of what a responsive web design is, if you already know what it is, you may skip this part and jump to the “Let’s code” section below. Well, for me, responsive web design is a way to show your web site’s content in an easy-to-understand manner regardless of what device views it.

For example, a visitor of your website must feel comfortable when viewing the same website for any type of devices (with different screen sizes) he has. Example of those devices include:

  • Android phones
  • iPhones
  • 7″ tablets
  • 10″ tablets
  • iPads
  • Desktop computers
  • and many more devices that can view a web page.

Other points to consider…

  • Your website should not have a horizontal scrollbar.
  • Users must not use the zoom tool to view your site’s contents.

By the way, if you want to test the live demo on different devices easily, you can use the tools described on this link: Responsive Web Design Testing Tools.

Let’s code.

Step 1: It is important to build your website for the smallest device possible first. Build the website for smart phones. You can view a live demo of our step 1 here.

<!DOCTYPE HTML>
<html>
     <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          <meta name="viewport" content="width=device-width">
         
          <title>Your Website</title>
         
          <style>
              
          /* misc start */
          *{
               margin:0px;
               padding:0px
          }
         
          body{
               font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
          }
         
          .media1140px{
               background-color:#CE9429;
          }
         
          .media768px{
               background-color:#EDD49A;
          }
         
          .media480px{
               background-color:#EFEF34;
          }
         
          .media300px{
               background-color:#82EAFF;
          }
         
          .media1140px, .media768px, .media480px, .media300px{
               padding:15px;
          }
         
          p{
               margin:0 0 20px 0;
          }
         
          .clearb{
               clear:both;
          }
          /* misc end */
         
         
         
         
         
         
          /* header start */
          #mainHeader{
               background-color:#82EAFF;
               padding:0.5em;
               overflow:auto;
          }
          
          /* to make our logo resize automatically */
          #responsiveLogo{
               width:100%;
          }
         
          #responsiveLogo img{
               max-height: 100%;
               max-width: 100%;
          }
          /* header end */
         
         
         
         
         
          /* navigation start */
          nav{
               float:left;
               width:100%;
          }
         
          nav ul{
               list-style-type:none;
               padding:0;
          }

          nav ul li{
         
          }

          nav ul li a{
               background-color:green;
               border:thin solid #fff;
               color:#fff;
               display:block;
               height:3em;
               line-height:3em;
               text-align:center;
               text-decoration:none;
               width:100%;
          }
         
          nav ul li a:hover{
               background-color:yellow;
               color:#000;
          }
          /* navigation end */
         
         
         
         
         
          /* middle section start */
          #mainSection{
               background-color: #D9F8F2;
               float: left;
               width: 96%;
          }
         
          #sideBox1{
               background-color: #C9A449;
               width: 96%;
          }
         
          #mainSection, #sideBox1{
               overflow: auto;
               padding:2%;
          }
          /* middle section end */
         
         
         
          /* footer start */
          footer{
               background-color:orange;
               height:50px;
               line-height:50px;
               text-align:center;
               width:100%;
          }
          /* footer end */
              
          </style>
         
     </head>
<body>

     <header id='mainHeader'>
    
          <div id='responsiveLogo'>
               <img src='images/logo4.png' />
          </div>
          <nav>
               <ul>
                    <li><a href="#home">Home</a></li>
                    <li><a href="#news">News</a></li>
                    <li><a href="#contact">Contact</a></li>
                    <li><a href="#about">About</a></li>
               </ul>
          </nav>
     </header>
    
     <section id='mainSection'>

          <article>
               <header>
                    <h2>About The Code Of A Ninja</h2>
                    <p>Posted on <time datetime="2003-01-01T16:31:24+02:00">January 1st, 2013</time> by <a href="#">Mike</a> - <a href="#comments">173 comments</a></p>
               </header>
               <p>
                    <div class='media1140px'>@media 1140px</div>
                    <div class='media768px'>@media 768px</div>
                    <div class='media480px'>@media 480px</div>
                    <div class='media300px'>@media 300px</div>
               </p>
               <p>
                    My name is Mike Dalisay, a 22 year old Software Developer (<a href="http://en.wikipedia.org/wiki/Web_developer">Web</a> and
                    <a href="http://developer.android.com/index.html">Android</a>) from The Philippines.
                    My posts here are mainly notes to self and for <i>anyone else</i> that may find them useful.
               </p>
               <p>
                    This blog contains programming tutorials, codes, demos, scripts, how-to's, tips, tricks, code downloads and other fun stuff
                    related to web and android apps <a href="http://en.wikipedia.org/wiki/Software_development">development</a>.
               </p>
               <p>
                    Most of my time is spent with PHP, MySQL, AJAX, HTML, CSS, jQuery, JavaScript, XML, Web Design, Android, JAVA and some
                    other Open source software projects related to Web and Android apps development.
               </p>
               <p>
                    You can leave a comment, <a href="http://twitter.com/ninjazhai">follow</a> or <a href="https://www.facebook.com/pages/the-code-of-a-ninja/107786425949934">subscribe</a>
                    to this blog. Take care. :) 
               </p>
          </article>

     </section>

     <aside id='sideBox1'>
          <h2>The Blogger</h2>
          <p>This is your side bar. You can add your information or links here.</p>
     </aside>

     <div class='clearb'></div>
    
     <footer>
          <p>Copyright 2013 - Game Note</p>
     </footer>

</body>
</html>

After doing the code above, our webpage is not yet responsive. You won’t see the magic even if you resize your browser. By the way, you can also include the CSS code as external file.

Step 2: Now let’s create the website layout for a type of device next to a smart phone, maybe we can consider a 7″ tablets as one. You can view a live demo of your step 2 here.

We’ll just add the following CSS:

/* 
-can be for 7 inch tablets
-This CSS will apply for devices with the minimum width of 480 pixels
 */
@media only screen and (min-width: 480px) {
     #mainHeader {
          background-color:#EFEF34;
     }
    
     nav ul li{
          float:left;
          width:25%;
     }
}

Now if you’ll resize your browser, you can see that your website is already responsive in two ways.

Step 3: Now we will create the website layout for another type of screen next to 7″ tablets, we can consider the iPad or 10″ tablets in portrait mode. Our step 3 live demo is here.

Please add the following CSS:

/*
-10 inch tablets
-This CSS will apply for devices with the minimum width of 768 pixels
*/
@media only screen and (min-width: 768px) {
     #mainHeader {
          background-color:#EDD49A;
     }
    
     #mainSection{
          float: left;
          width: 61%;
     }
    
     #sideBox1{
          float: right;
          width: 30%;
     }
    
}

Now our website is responsive in three ways. Try to re-size your browser again.

Step 4: Now we will create the website for desktop computers, laptops or 10″ tablets in landscape mode.

/*
-Desktop computers
-This CSS will apply for devices with the minimum width of 1140 pixels
*/
@media only screen and (min-width: 1140px) {
     #mainHeader {
          background-color:#CE9429;
     }
    
     #responsiveLogo{
          float:left;
          width:30%;
     }
    
     nav{
          float:left;
          width:70%;
     }
    
     nav ul{
          margin:1.5em 0 0 0;
     }
}

Complete web page code:

<!DOCTYPE HTML>
<html>
     <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
          <meta name="viewport" content="width=device-width">
         
          <title>Your Website</title>
         
          <style>
              
          /* misc start */
          *{
               margin:0px;
               padding:0px
          }
         
          body{
               font-family:"Lucida Sans Unicode", "Lucida Grande", sans-serif;
          }
         
          .media1140px{
               background-color:#CE9429;
          }
         
          .media768px{
               background-color:#EDD49A;
          }
         
          .media480px{
               background-color:#EFEF34;
          }
         
          .media300px{
               background-color:#82EAFF;
          }
         
          .media1140px, .media768px, .media480px, .media300px{
               padding:15px;
          }
         
          p{
               margin:0 0 20px 0;
          }
         
          .clearb{
               clear:both;
          }
          /* misc end */
         
         
         
         
         
         
          /* header start */
          #mainHeader{
               background-color:#82EAFF;
               padding:0.5em;
               overflow:auto;
          }
         
          #responsiveLogo{
               width:100%;
          }
         
          #responsiveLogo img{
               max-height: 100%;
               max-width: 100%;
          }
          /* header end */
         
         
         
         
         
          /* navigation start */
          nav{
               float:left;
               width:100%;
          }
         
          nav ul{
               list-style-type:none;
               padding:0;
          }

          nav ul li{
         
          }

          nav ul li a{
               background-color:green;
               border:thin solid #fff;
               color:#fff;
               display:block;
               height:3em;
               line-height:3em;
               text-align:center;
               text-decoration:none;
               width:100%;
          }
         
          nav ul li a:hover{
               background-color:yellow;
               color:#000;
          }
          /* navigation end */
         
         
         
         
         
          /* middle section start */
          #mainSection{
               background-color: #D9F8F2;
               float: left;
               width: 96%;
          }
         
          #sideBox1{
               background-color: #C9A449;
               width: 96%;
          }
         
          #mainSection, #sideBox1{
               overflow: auto;
               padding:2%;
          }
          /* middle section end */
         
         
         
          /* footer start */
          footer{
               background-color:orange;
               height:50px;
               line-height:50px;
               text-align:center;
               width:100%;
          }
          /* footer end */
         
         
         
         
         
         
         
          /* @media start */
         
          /* we don't need to specify for smartphones, that's our default layout */
         
          /*
          -7 inch tablets
          -This CSS will apply for devices with the minimum width of 480 pixels
          */
          @media only screen and (min-width: 480px) {
               #mainHeader {
                    background-color:#EFEF34;
               }
              
               nav ul li{
                    float:left;
                    width:25%;
               }
          }
         
          /*
          -10 inch tablets
          -This CSS will apply for devices with the minimum width of 768 pixels
          */
          @media only screen and (min-width: 768px) {
               #mainHeader {
                    background-color:#EDD49A;
               }
              
               #mainSection{
                    float: left;
                    width: 61%;
               }
              
               #sideBox1{
                    float: right;
                    width: 30%;
               }
              
              
          }
         
          /*
          -Desktop computers
          -This CSS will apply for devices with the minimum width of 1140 pixels
          */
          @media only screen and (min-width: 1140px) {
               #mainHeader {
                    background-color:#CE9429;
               }
              
               #responsiveLogo{
                    float:left;
                    width:30%;
               }
              
               nav{
                    float:left;
                    width:70%;
               }
              
               nav ul{
                    margin:1.5em 0 0 0;
               }
          }
         
          /* @media end */
              
          </style>
         
     </head>
<body>

     <header id='mainHeader'>
    
          <div id='responsiveLogo'>
               <img src='images/logo4.png' />
          </div>
          <nav>
               <ul>
                    <li><a href="#home">Home</a></li>
                    <li><a href="#news">News</a></li>
                    <li><a href="#contact">Contact</a></li>
                    <li><a href="#about">About</a></li>
               </ul>
          </nav>
     </header>
    
     <section id='mainSection'>

          <article>
               <header>
                    <h2>About The Code Of A Ninja</h2>
                    <p>Posted on <time datetime="2003-01-01T16:31:24+02:00">January 1st, 2013</time> by <a href="#">Mike</a> - <a href="#comments">173 comments</a></p>
               </header>
               <p>
                    <div class='media1140px'>@media 1140px</div>
                    <div class='media768px'>@media 768px</div>
                    <div class='media480px'>@media 480px</div>
                    <div class='media300px'>@media 300px</div>
               </p>
               <p>
                    My name is Mike Dalisay, a 22 year old Software Developer (<a href="http://en.wikipedia.org/wiki/Web_developer">Web</a> and
                    <a href="http://developer.android.com/index.html">Android</a>) from The Philippines.
                    My posts here are mainly notes to self and for <i>anyone else</i> that may find them useful.
               </p>
               <p>
                    This blog contains programming tutorials, codes, demos, scripts, how-to's, tips, tricks, code downloads and other fun stuff
                    related to web and android apps <a href="http://en.wikipedia.org/wiki/Software_development">development</a>.
               </p>
               <p>
                    Most of my time is spent with PHP, MySQL, AJAX, HTML, CSS, jQuery, JavaScript, XML, Web Design, Android, JAVA and some
                    other Open source software projects related to Web and Android apps development.
               </p>
               <p>
                    You can leave a comment, <a href="http://twitter.com/ninjazhai">follow</a> or <a href="https://www.facebook.com/pages/the-code-of-a-ninja/107786425949934">subscribe</a>
                    to this blog. Take care. :) 
               </p>
          </article>

     </section>

     <aside id='sideBox1'>
          <h2>The Blogger</h2>
          <p>This is your side bar. You can add your information or links here.</p>
     </aside>

     <div class='clearb'></div>
    
     <footer>
          <p>Copyright 2013 - Game Note</p>
     </footer>

</body>
</html>

Download Source Code

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

Some screenshots of our output:

Page header smartphone screenshot – landscape mode

Page header smartphone screenshot – landscape mode

Footer screenshot from my smartphone in landscape mode.

Footer screenshot from my smartphone in landscape mode.

Header screenshot from my smartphone  in portrait mode.

Header screenshot from my smartphone
in portrait mode.

Body section screenshot from my Smartphone in  portrait mode.

Body section screenshot from
my Smartphone in portrait mode.

Footer screenshot from  my smartphone in portrait mode.

Footer screenshot from
my smartphone in portrait mode.

Screenshot from my 10.1 Android tablet in portrait mode.

Screenshot from my 10.1 Android tablet in portrait mode.

Credits: Image from Game Note.

Home Lists+

JavaScript Array CRUD Example

Our code for today will give us example on how to Create, Read, Update and Delete (CRUD) items in a JavaScript array. This technique will give you full control over the fields and values of each array item.

Example use of this code is when you have long rows of input elements and wanted to detect only the elements with inputted values, get their id, value and other related information. You won"t have to loop through all the input elements to check if there are inputted values.

This is because, you can instantly add an item to the array if the value was inputted, edit it when the value were changed, delete it when the value were removed and then read it for posting or later use. We can achieve better performance. Here is a video demo:

JavaScript Crud Example

Our index.php code – here you can see the our JavaScript CRUD functions (with some jQuery help) and sample HTML.

<html>
    <head>
        <title>JS Array CRUD - https://codeofaninja.com</title>
    </head>
   
<body>

<!–
    -example row of items
    -id is the item number
    -common class name
–>
Item 1 <input type="text" id="1" class="item" /><br />
Item 2 <input type="text" id="2" class="item" /><br />
Item 3 <input type="text" id="3" class="item" /><br />
Item 4 <input type="text" id="4" class="item" /><br />
Item 5 <input type="text" id="5" class="item" /><br />

<br />
<br />

<!– display the operations here –>
<b>Actions:</b>
<div id="status"></div>

<br />

<!– display the array length and items –>
<b>All Items:</b>
<div id="results"></div>

</body>
</html>

Now, put the following code before the closing body tag of our HTML code above.

<!– include the jquery –>
<script type="text/javascript" src="jquery.min.js"></script>

<script type="text/javascript">
    // initialize array as global variable
    var items = [];
   
    $(document).ready(function(){
   
        //we use the jquery blur event
        $(".item").blur(function(){
       
            //in this example, the item id is the id attribute of the element
            var item_id = $(this).attr("id");
           
            //item value is the inputtedvalue
            var item_value = $(this).val();
           
            //then process the item
            process_item(item_id,item_value);
        });
       
    });
   
    // ———— functions [START] ————

    // process item, usually based in item id
    function process_item(item_id,item_value){
       
        if(item_value==""){
            //if item value is empty, delete from the array
            delete_item(item_id);
        }else if(checkIfExists(item_id)){
            //search if item_id exists in the array
            //if item exists, edit it
            edit(item_id,item_value);
        }else if(!checkIfExists(item_id)){
            //if item does not exist, add it
            add(item_id,item_value);
        }
       
        //read the items
        showAllItems();
    }
   
    // ADD
    function add(item_id,item_value){
        items.push({
            "item_id" : item_id,
            "item_value" : item_value
        });
        $("#status").text("Successfully added.");
    }

    // EDIT
    function edit(item_id,item_value){
       
        //delete first
        items.remove("item_id", item_id);
       
        //then add again
        items.push({
            "item_id" : item_id,
            "item_value" : item_value
        });
        $("#status").text("successfully edited.");
           
    }
   
    // DELETE
    function delete_item(item_id){
        items.remove("item_id", item_id);
        $("#status").text("Successfully deleted.");
    }
   
    // READ
    function showAllItems(){
       
        //clear results text
        $("#results").text("");
       
        var arr_len = items.length;
       
        // display also the array length
        $("#results").append("Array len: " + arr_len+ "<br />");
       
        //loop through the array to read the items
        for(var x=0; x<arr_len; x++){
            var item_id = items[x]['item_id'];
            var item_value = items[x]['item_value'];
           
            //append to results div to display
            $("#results").append("item_id: " + item_id + " >>> item_value: " + item_value + "<br />");
        }
    }
   
    function checkIfExists(check_item_id){
       
        //get the array length first
        var arr_len = items.length;
       
        //search the array
        //there might be another way
        for(var x=0; x<arr_len; x++){
            var item_id = items[x]['item_id'];
            var item_value = items[x]['item_value'];
           
            if(check_item_id==item_id){
                //it means the item exists
                return true;
            }
        }
       
        return false;
    }
   
    //needs a remove function
    Array.prototype.remove = function(name, value) {
        array = this;
        var rest = $.grep(this, function(item){
            return (item[name] != value);  
        });

        array.length = rest.length;
        $.each(rest, function(n, obj) {
            array[n] = obj;
        });
    };
    // ———— functions [END] ————
</script>

Convert to JSON

You can also convert the array to a JSON this way:

Add the json2.js file from here.

<script type="text/javascript" src="json2.js"></script>

…and do this

var json_str= JSON.stringify(items);

Posting the Array

If you want to post the resulting array..

1. Prepare the PHP file that will receive the post value. I created get_post.php with the code:

<?php
//just to display raw values
echo "<pre>";
    print_r($_POST);
echo "</pre>";

//access the values
foreach($_POST['items'] as $item){
    echo $item['item_id'] . ":" . $item['item_value'] . "<br />";
}
?>

2. Add a button and a new div area to our index.php

The button:

<input type="button" value="Post Array" id="post" />

Div area where we can see the posted values..

<!– display the posted items value –>
<b>Posted Items:</b>
<div id="postedItems"></div>

3. Clicking the post array button will show the posted value to postedItems div.

$("#post").click(function(){
    $.ajax({
        url: "get_post.php",
        data: {"items": items},
        type: "post",
        success: function(data) {
            $("#postedItems").append(data);
        }
    });
});

The value posted to get_post.php look like this:

Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [item_id] => 1
                    [item_value] => john
                )

            [1] => Array
                (
                    [item_id] => 3
                    [item_value] => michael
                )

        )

)

Download Source Code

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

Thank you for learning from our post about: JavaScript CRUD example!

Home jQuery

FbAlbumPreview jQuery Plugin

Hi there guys! Today I want to share with you a jQuery plugin that I made.

This jQuery plugin will enable your users to preview your web albums instantly.

My inspiration here is the Facebook albums, if you have a Facebook account (I’m sure you have, haha!) and wanted to view the list of albums, you can experience this functionality:

For me, above is a very simple Facebook feature and yet, it’s awesome. It is very convenient for a user to have an album preview just by doing a hover.
Here’s our index.html code:

<html>
    <head>
        <title>FB Album Preview jQuery Plugin by https://codeofaninja.com/</title>
        <!– add some styles –>
        <link rel=‘stylesheet’ type=‘text/css’ href=‘css/style.css’ />
       
    </head>
<body>

<h3>
    Demo of FB Album Preview jQuery Plugin by <a href=‘https://codeofaninja.com/’>The Code Of A Ninja</a>
</h3>


<!– -You can generate all these HTML and JS codes using your server side script -The number of photos or thumbnails to be previewed depends on you –>

<div id=‘mainContent’>

    <!– album # 1 –>

<div class=‘albumDetails’>

<div class=“fbAlbum”>
            <!– the first image is the album cover photo –>
            <img class=“active” src=“images/1.jpg” />
            <img src=“images/2.jpg” />
            <img src=“images/3.jpg” />
            <img src=“images/4.jpg” />
            <img src=“images/5.jpg” />
        </div>


<div class=‘albumTitle’><a href=”>Profile Picture</a></div>


<div class=‘photosNum’>5 photos</div>

    </div>

   
    <!– album # 2 –>

<div class=‘albumDetails’>

<div class=“fbAlbum”>
            <!– the first image is the album cover photo –>
            <img class=“active” src=“images/6.jpg” />
            <img src=“images/7.jpg” />
            <img src=“images/8.jpg” />
        </div>


<div class=‘albumTitle’><a href=”>Mobile Uploads</a></div>


<div class=‘photosNum’>3 photos</div>

    </div>

   
    <!– album # 3 –>

<div class=‘albumDetails’>

<div class=“fbAlbum”>
            <!– the first image is the album cover photo –>
            <img class=“active” src=“images/9.jpg” />
            <img src=“images/10.jpg” />
            <img src=“images/11.jpg” />
            <img src=“images/12.jpg” />
        </div>


<div class=‘albumTitle’><a href=”>Wall Photos</a></div>


<div class=‘photosNum’>4 photos</div>

    </div>

   
</div>


<!– include jQuery library and our FB album preview plugin –>
<script src=“js/jquery.min.js”></script>
<script src=“js/fb.album.preview.js”></script>

<!– this is how we’re gonna use the plugin –>
<script type=‘text/javascript’>
$(document).ready(function(){
    // since all albums images container are under the class ‘fbAlbum’,
    // that’s what we are gonna user as the selector
    $(‘.fbAlbum’).FbAlbumPreview();
});
</script>

</body>
</html>

Our CSS code:

body{
    font-family: ‘helvetica neue’, helvetica, arial, sans-serif;
}

.fbAlbum {
    position:relative;
    width:206px;
    height:206px;
    cursor:pointer;
}

.fbAlbum IMG {
    position:absolute;
    top:0;
    left:0;
    z-index:8;
    width:206px;
    height:206px;
}

.fbAlbum IMG.active {
    z-index:10;
}

.fbAlbum IMG.last-active {
    z-index:9;
}
           
.albumDetails{
    float:left;        
    width:206px;
    height:270px;
    margin:20px;
}

.albumTitle{
    font-family: ‘helvetica neue’, helvetica, arial, sans-serif;
    white-space: nowrap;
    font-weight:bold;
    font-size:14px;
    padding:10px 0 5px 0;
    text-align:center;
   
}

.albumTitle a{
    text-decoration:none;
    color:#3B5998;
}

.albumTitle a:hover{
    text-decoration:underline;
}

.photosNum{
    color:gray;
    line-height:19px;
    font-size:11px;
    text-align:center;
    font-family: ‘lucida grande’, tahoma, verdana, arial, sans-serif;
}

#mainContent{
    width:750px;
    margin:0 auto;
    margin-top:100px;
}

.clearb{
    clear:both;
}

Customization code: Yes, you can supply values to customize the view and fade speed effect of this plugin. The default is viewSpeed = 1000 and fadeSpeed = 500. viewSpeed should always be greater than fadeSpeed.

   $(‘.fbAlbum’).FbAlbumPreview({
        viewSpeed: 800,
        fadeSpeed: 400
    });

viewSpeed – refers to how long the user can take a look at the thumbnail image
fadeSpeed – how long the transition (fade effect) from one image to another will take place

FbAlbumPreview jQuery plugin Code (compressed)

/*FbAlbumPreview jQuery Plugin by Mike Dalisay - https://codeofaninja.com/ */
(function(a) {
    a.fn.FbAlbumPreview = function(b) {
        var c = a.extend({
            viewSpeed: 1e3,
            fadeSpeed: 500
        }, b);
        return this.each(function() {
            var b;
            var d = c.fadeSpeed;
            var e = false;
            a(this).hover(function() {
                var f = a(this);
                b = setInterval(function() {
                    f.find("IMG").show();
                    var a = f.find("IMG.active");
                    if (a.length == 0) {
                        a = f.find("IMG:last")
                    }
                    var b = a.next().length ? a.next() : f.find("IMG:first");
                    a.addClass("last-active");
                    b.css({
                        opacity: 0
                    }).addClass("active").animate({
                        opacity: 1
                    }, d, function() {
                        a.removeClass("active last-active");
                        e = true
                    })
                }, c.viewSpeed)
            }, function() {
                clearInterval(b);
                if (e == true) {
                    var c = a(this);
                    c.find("img").hide();
                    c.find("IMG.active").removeClass("active");
                    var f = c.find("IMG:first").fadeOut(d).fadeIn(d).addClass("active");
                    e = false
                }
            })
        })
    }
})(jQuery)

Download Source Codes
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 FbAlbumPreview jQuery Plugin.

Home jQuery

Convert a DIV Area to an Editable HTML Form

Hello guys! today we are going to do a code that converts a DIV area to an editable HTML form and save the changes to the database.

We are going to use jQuery, PHP & MySQL ofcourse.

My inspiration for this post is Youtube!

For beginners, this post covers some useful stuff like:

  • jQuery on(), post(), hover(), text(), val(), serialize(), css(), show() and hide() function examples
  • For PDO, we'll cover how to use the SELECT and UPDATE commands for database interaction.
  • You will also learn or see an example on how to submit form without page refresh (AJAX).

Our database would look like this:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `gender` varchar(6) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=56 ;
–
– Dumping data for table `users`
–

INSERT INTO `users` (`id`, `firstname`, `lastname`, `gender`, `username`, `password`, `modified`) VALUES
(28, 'John', 'Dalisay', 'Male', 'john', 'john123′, '2012-07-23 13:26:39′);

The Code

our libs/db_connect.php code, change as you needed.

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

our index.php code:

<html>
    <head>
        <title>Div to Form – https://codeofaninja.com/</title>
        <!–just to include some styles –>
        <link rel="stylesheet" type="text/css" href="css/style.css" />
    </head>
<body>
<div id='banner'>
    <h2>Code of a Ninja Programming Blog</h2>
    <div>Converting a div to an editable HTML form and save changes to database</div>
</div>

<?php
//just getting the id of the user to be edited
$id = $_REQUEST['id'];

//connect to database
include 'libs/db_connect.php';

try {

    //prepare query
    $query = "select id, firstname, lastname, gender from users where id = ? limit 0,1″;
    $stmt = $con->prepare( $query );
    
    //this is the first question mark on the query above
    $stmt->bindParam(1, $id);
    
    //execute our query
    $stmt->execute();
    
    //store retrieved row to $row variable
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    
    //values to fill up our form
    $firstname = $row['firstname'];
    $lastname = $row['lastname'];
    $gender = $row['gender'];
    
}catch(PDOException $exception){ //to handle error
    echo "Error: " . $exception->getMessage();
}

?>
<!–start of our form –>
<form id='user_form'>

<!–id field is hidden, this is used to identify what row is to be edited–>
<input type='hidden' value='<?php echo $id; ?>' name='id'/>

<!–
    -just a form made with divs
    -when this div was clicked, it will be a form
–>
<div id='form_div'>
    
    <div class='field'>
        <div class='field_lbl'>Firstname:</div> <!–field name divs –>
        <div class='field_val'>
            <div class='field_div'>
                <!–
                    -this shown on page load
                    -and is hidden when the form_div was clicked
                    -and will be shown again when the user clicked anywhere outside the form_div or cancel button
                –>
                <div id='firstname_text'><?php echo $firstname; ?></div>
            </div>
            <div class='field_input'>
                <!–
                    -this is hidden on page load
                    -and is shown when form_div was clicked
                    -and will be hidden again when the user clicked anywhere outside the form_div or cancel button
                –>
                <input type='text' value='<?php echo $firstname; ?>' name='firstname' id='firstname'/>
            </div>
            <div class='clear_fix'></div>
        </div>
        <div class='clear_fix'></div>
    </div>
    <div class='clear_fix'></div>
    
    <!–same explanation above are given to these next fields–>
    <div class='field'>
        <div class='field_lbl'>Lastname:</div>
        <div class='field_val'>
            <div class='field_div'>
                <div id='lastname_text'><?php echo $lastname; ?></div>
            </div>
            <div class='field_input'><input type='text' value='<?php echo $lastname; ?>' name='lastname' id='lastname' /></div>
            <div class='clear_fix'></div>
        </div>
        <div class='clear_fix'></div>
    </div>
    <div class='clear_fix'></div>
    
    <div class='field'>
        <div class='field_lbl'>Gender:</div>
        <div class='field_val'>
            <div class='field_div'>
                <div id='gender_text'><?php echo $gender; ?></div>
            </div>
            <div class='field_input'>
                <select name='gender' id='gender'>
                    <option <?php if($gender == "Male") echo "selected";  ?> >Male</option>
                    <option <?php if($gender == "Female") echo "selected";  ?>>Female</option>
                </select>
            </div>
            <div class='clear_fix'></div>
        </div>
        <div class='clear_fix'></div>
    </div>
    <div class='clear_fix'></div>
    
    <!–
    -these buttons are hidden on page load
    -they are shown when form_div was clicked
    -and will be hidden again when the user clicked anywhere outside the form_div or cancel button
    —>
    <div class='btns'>
        <input type='button' value='Save' id='save_btn' />
        <input type='button' value='Cancel' id='cancel_btn' />
    </div>
    
</div>

</form>

<script src="js/jquery.min.js "></script>
<script type='text/javascript'>
$( document ).ready( function(){

    enable_hover(); //hover effect is enabled on page load

    $('#form_div').click(function(){
        edit_mode();
    });
    
    //when clicked the cancel button
    $('body').on('click', '#cancel_btn', function(){
        normal_mode(); //back to normal mode
    });
    
    //we used the jquery delegate func for live events
    $('body').on('click', '#save_btn', function(){
        
        //save first here
        //get the current values
        var fn = $('#firstname').val();
        var ln = $('#lastname').val();
        var gender = $('#gender').val();
        
        //the make it appear in the UI
        $('#firstname_text').text(fn);
        $('#lastname_text').text(ln);
        $('#gender_text').text(gender);
        
        //save the actual data
        //we use jquery serialize to serialize the form and easily get the form values
        //this is how to submit or post form without page refresh
        $.post("save.php", 
            $("#user_form").serialize(),
            function(data) {
                //you can do any event you want here
                alert(data); //alert that the date were saved
                normal_mode(); //back to normal mode
            });
            
    });
    
    //this way we can detect if the user clicked outside the form_div area
    $("body").click(function(e) {
        if (e.target.id == "form_div" || $(e.target).parents("#form_div").size()) { 
            //if clicked inside form_div area,
            //do nothing
        } else {
            //if the user clicked outside the form_div area, 
            //we'll be in normal mode
            normal_mode();
        }
    });
   

    
});

function edit_mode(){

    $('#form_div').css({ 'background-color' : '#fff' }); //just make a white background
    $('#form_div').unbind('hover'); //disable hover
    
    $('.field_div').hide(); //hide the text
    $('.field_input').show(); //show the form element
    $('.btns').show(); //show the buttons

}

//the normal state is the appearance of the page/element when it was first loaded
function normal_mode(){
    enable_hover(); //enable the hover effect again
    $('.field_div').show(); //show the texts
    $('.field_input').hide(); //hide the input elements
    $('.btns').hide(); //hide the buttons
}

//hover effect is used when NOT in 'edit form' mode
//we unbind this effect when we are in the 'edit form' mode
function enable_hover(){
    $('#form_div').hover(
        function(){ //when we hover form_div, bg will be gray with a bit of rounded corners
            $(this).css({
                    'background-color' : '#dcdcdc',
                    '-moz-border-radius' : '5px',
                    'border-radius' : '5px'
                    });
        },
        function(){ //when mouse is not hovered, bg will be transparent
            $(this).css({'background-color' : 'transparent'});
        }
    );
}
</script>

</body>
</html>

our save.php code:

<?php
//this is where the data were updated/saved
//connect to database
include 'libs/db_connect.php';

try{
    
    //write query
    //in this case, it seemed like we have so many fields to pass and 
    //its kinda better if we'll label them and not use question marks
    //like what we used here
    $query = "update 
                users 
            set 
                firstname = :firstname, 
                lastname = :lastname,
                gender = :gender
            where id = :id";

    //prepare query for excecution
    $stmt = $con->prepare($query);

    //bind the parameters
    $stmt->bindParam(':firstname', $_POST['firstname']);
    $stmt->bindParam(':lastname', $_POST['lastname']);
    $stmt->bindParam(':gender', $_POST['gender']);
    $stmt->bindParam(':id', $_POST['id']);
    
    // Execute the query
    if( $stmt->execute() ){
        echo "Record was updated.";
    
    }else{
        echo "Unable to update record.";
    }

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

our style.css file:

body{
    margin:0;
    font-family:arial, verdana, tahoma;
}
#banner{
    margin:0 0 50px 0;
    padding:20px;
    width:100%;
    height:100px;
}

#form_div{
    padding:10px;
    width:500px;
    margin:0 auto;
}

.field{
    padding: 10px;
}

.field_lbl{
    float:left;
    margin:0 10px 0 0;
    width:80px;
    font-weight:bold;
}

.field_val{
    float:left;
}

.field_div{
    display:block;
}

.field_input{
    display:none;
}

.btns{
    display:none;
    margin:0 0 0 8px;
}

.clear_fix{
    clear:both;
}

Thank you guys for your kind comments, messages and suggestions. I really appreciate it!

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 Convert a DIV Area to an Editable HTML Form.