Posts

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.

Home jQuery

Google Plus Style Notification Box Tutorial

Hi guys! I like the Google+ notification box and lately I wondered how to code a notification box that look like something like that.

I love its simple design and box animation with easing.

So I decided to create my own version.

Today we are going to do a script that will look like the Google+ notification box. I was able to achieve this using jQuery, jQuery easing plugin and PHP.

You should see the live demo before coding:

The database I used (notifications.sql) is included in the code download. Here are the files I used:

  • css/style.css - stylesheet
  • img/ajax-loader.gif - loader image to show while loading the actual notification
  • js/jquery.easing.1.3.js - the plugin used for animation (easing)
  • js/jquery-1.7.1.min.js - our favorite JavaScript library (you can also use the google hosted)
  • config_open_db.php - connect to database
  • index.php - load the notification list and show/hide the box
  • item.php - load the actual notification

index.php code

<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="content-type" content="text/html; charset=UTF-8">
		<title>Google plus style notification box</title>
		<link rel="stylesheet" type="text/css" href="css/style.css" />
	</head>

<body>

	<div id='bar'>

		<!-- show_notifications when clicked, will show or hide the notification box with fade effect -->
		<div id='show_notifications'>Notifications</div>

		<div style='clear:both;'></div>

		<!-- wrapper is the notification box -->
		<div id="wrapper">

			<!-- div1 will hold the notification list -->
			<div class="full" id="div1">
				<div id='box_header'>
					<div id='noti_text'>Notifications</div>

					<!-- ajax loader was shown when a notification item was clicked -->
					<div id='loader'><img src='img/ajax-loader.gif' /></div>

					<div id='site_link'>
						<a href='https://www.codeofaninja.com/'>+Code of a Ninja</a> &#9658;
					</div>
				</div>

				<div id='noti_list'>
					<?php
					// php code will be here
					?>
				</div>

				<div id='box_footer'>
					<!-- Change link this to your notifications page -->
					<a href='https://www.codeofaninja.com/2012/03/goole-plus-style-notification-box.html?your-link-to-all-notifications/'>View all notifications</a> &#9658;
				</div>
			</div>

			<!-- div2 will hold the actual notification -->
			<div class="full" id="div2">
				<div id='box_header'>
					<div id='noti_text'>&#9668; <a href='#'><span id='back_to_noti'>Back to Notifications</span></a></div>
					<div id='site_link'>
						<a href='https://www.codeofaninja.com/'>+Code of a Ninja</a> &#9658;
					</div>
				</div>

				<div id='actual_notification'>
					<!-- Here is where the actual notification will be loaded -->
				</div>

				<div id='box_footer'>
					<!-- Change link this to your notifications page -->
					<a href='http://yourdomain.com/your-link-to-all-notifications/'>View all notifications</a> &#9658;
				</div>
			</div>


		</div>
	</div>

	<div style='margin-top:20px;'>
		Click the "Notifications" button to show or hide the box.
	</div>

	<div style='margin-top:300px;'>
		<a href='https://www.codeofaninja.com/2012/03/goole-plus-style-notification-box.html'>Tutorial Link Here</a>
	</div>

<!-- javascript code will be here -->

</body>
</html>

PHP Code

Replace "PHP code will be here" line above with the following code.

//this will load the notifications in the database
include 'config_open_db.php';

//selecting record, you can use the limit clause here
//$_GET['owner_id'] is just an example user id passed via url
//you should use session variable here
$sql = "select * from notifications where owner_id = '" . $mysqli->real_escape_string( $_GET['owner_id'] ) . "'";

//query the database
$result = $mysqli->query( $sql );

//count how many records found
$num_results = mysqli_num_rows( $result );

if($num_results>0){ //check if more than 0 record found
	while( $row = $result->fetch_assoc()  ){
		extract($row);

		//display the notification item
		echo "<div class='noti_item'>";

			//noti_id will identify what notification item was clicked
			//which will be used to load the actual notification for the next screen
			echo "<div class='noti_id'>{$id}</div>";
			echo $notification;
		echo "</div>";
	}
}else{
	echo "No notification found.";
}

JavaScript Code

Replace "javascript code will be here" line above with the following code.

<!-- include the jQuery library and jQuery easing plugin -->
<script type='text/javascript' src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript' src="js/jquery.easing.1.3.js"></script>

<!-- this script will do the animations and loading actual notificaiton -->
<script type='text/javascript'>
$(window).load(function(){
	//show or hide the notification box
	$('#show_notifications').click(function(){
		$('#wrapper').fadeToggle();
	});

	//prepare/show #div2 on load
	$('#div2').css('left','440px').show();


	$('.noti_item').click(function(){

		//show the loader while waiting for the actual notificaiton to be loaded
		$('#loader').show();
		var noti_id = $(this).find('.noti_id').text();

		//item.php will load the actual notification based on the notification id
		$("#actual_notification").load("item.php?id=" + noti_id, function(){

			//after loading the actual notification,
			//hide the loader when the actual notification was loaded
			$('#loader').hide();

			//animate the box
			//hide #div1 (notification list)
			$('#div1').animate(
				{ left: '-440px' },{
					duration: '350',
					easing: 'easeOutQuint'
			});

			//then show #div2(actual notification)
			$('#div2').animate(
				{ left: 0 }, {
					duration: '350',
					easing: 'easeOutQuint'
			});

		});

	});

	//going back to notification list
	$('#back_to_noti').click(function(){

		//hide #div2 (actual notification)

		$('#div2').animate(
			{ left: '440px' },{
				duration: '350',
				easing: 'easeOutQuint'
		});

		//then show #div1 (notification list)
		$('#div1').animate(
			{ left: 0 }, {
				duration: '350',
				easing: 'easeOutQuint'
		});

		return false;
	});

});

</script>

item.php code

<?php
include 'config_open_db.php';

//selecting record
$sql = "select * from notifications where id = '" . $mysqli->real_escape_string( $_GET['id'] ) . "'";

//query the database
$result = $mysqli->query( $sql );

//count how many records found
$num_results = $result->num_rows;

if($num_results >0){ //check if more than 0 record found
    while( $row = $result->fetch_assoc() ){
        extract($row);
        echo "<div class='noti_indi'>";
            echo "<div class='noti_id'>{$id}</div>";
            echo $notification;
        echo "</div>";
    }
}else{
    echo "No notification found.";
}
?>

CSS code

body{
    font-family:arial;
    font-size:14px;
    padding:0;
    margin:0;
}

#bar{
    background-color:#f1f1f1;
    height:72px;
    border-bottom:thin solid #c0c0c0;
    width:100%;
}

#show_notifications{
    padding:8px;
    border:1px solid #c0c0c0;
    background-color:#fff;
    float:right;
    margin:20px 10px 5px 0;
    cursor:pointer;
    -moz-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 5px;
    font-weight:bold;
}

#loader{
    float:left;
    margin-left:10px;
    display:none;
}

#wrapper{
    width:440px;
    overflow:hidden;
    position:relative;
    height:300px;
    float:right;
    margin:0 10px 0 0;
    display:none;
}

.full{
    position:absolute;
    width:100%;
}

#div1{
    left:0px;
    padding-bottom:35px;
}

#div2{
    display:none;
    background:#FFFF00;
    left:0px;
    padding-bottom:35px;
}

#box_header{
    height:15px;
    width:418px;
    border:thin solid #c0c0c0;
    line-height:15px;
    background-color:#fff;
    padding:10px;
}

#box_footer{
    height:15px;
    width:418px;
    position:absolute;
    bottom:4px;
    border:thin solid #c0c0c0;
    background-color:#fff;
    padding:10px;
    text-align:center;
    color:#4067C9;
}

#box_footer a{
    color:#4067C9;
    text-decoration:none;
}

#box_footer a:hover{
    text-decoration:underline;
}

#noti_text{
    float:left;
    font-weight:bold;
    color:#4067C9;
}

#noti_text a{
    color:#4067C9;
    text-decoration:none;
}

#noti_text a:hover{
    text-decoration:underline;
}

#site_link{
    float:right;
    color:#4067C9;
}

#site_link a{
    color:#4067C9;
    text-decoration:none;
}

#site_link a:hover{
    text-decoration:underline;
}

.noti_item{
    width:400px;
    height:56px;
    line-height:56px;
    border-bottom:thin solid #c0c0c0;
    border-left:thin solid #c0c0c0;
    padding:10px;
}

.noti_indi{
    width:418px;
    border-bottom:thin solid #c0c0c0;
    padding:10px;
}

.clear{
    clear:both;
}

#noti_list{
    height:232px;
    overflow-y:visible;
    overflow-x:hidden;
    border-right:thin solid #c0c0c0;
    background-color:#F0F0F0;
    cursor:pointer;
}

#actual_notification{
    height:232px;
    overflow-y:visible;
    overflow-x:hidden;
    background-color:#F0F0F0;
    border-left:thin solid #c0c0c0;
    border-right:thin solid #c0c0c0;
}

.noti_id{
    display:none;
}

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 Google Plus Style Notification Box Tutorial.

Home jQuery

jQuery Redirect onClick Event (New or Same Window)

jQuery Quick Tip: This time I'm gonna show you how to redirect a page to another page or website when a user selected a value from a dropdown list and clicked a button.

We have two buttons here, the first one will redirect you to a website in the same page and the second one will redirect you in new tab (or window, in safari.)

jquery redirect onclick event to a page

Here's the live demo and code:

jQuery Redirect onClick Step by Step

Step 1: Prepare basic HTML page code.

<!doctype html>
<html>
   <head>
      <title>jQuery Redirect OnClick</title>
   </head>
<body>

</body>
</html>

Step 2: Put a drop down list of URLs you want your page to redirect.

<!--
  Here are our form elements,
  we have the select box / dropdown list
  which contains our URLs or links
-->
<select id="websites" style="width:200px;">
  <option value="http://demos.codeofaninja.com/tutorials/jQuery/get_dynamic_div_height.php">Get Dynamic</option>
  <option value="http://google.com">Google</option>
  <option value="https://codeofaninja.com">Blog</option>
  <option value="http://apple.com">Apple</option>
</select>

Step 3: Put the buttons for opening the URL in the same window or another window or tab.

<!--
  And our buttons, the first one is "Open In Same Window"
  which opens the link selected on the dropdown in the same window.
 
  The other button is the "Open In New Tab" which opens the link in
  new tab (or window in safari)
-->
<input type="button" value="Open In Same Window" id="open_same_window" />
<input type="button" value="Open In New Tab" id="open_new_tab" />

Step 4: Include jQuery library and basic jQuery code.

<!-- include our library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {

});
</script>

Step 5: Inside the basic jQuery code $(document).ready(function() {..., put the button click event triggers.

//this will be triggered when the first button was clicked
$("#open_same_window").click(function(){
  //this will find the selected website from the dropdown
  var go_to_url = $("#websites").find(":selected").val();
 
  //this will redirect us in same window
  document.location.href = go_to_url;
});

//this will be triggered when the second button was clicked
$("#open_new_tab").click(function(){
  //this will find the selected website from the dropdown
  var go_to_url = $("#websites").find(":selected").val();
 
  //this will redirect us in new tab
  window.open(go_to_url, '_blank');
});

Complete jQuery Redirect onClick Page

 <html>
   <head>
      <title>jQuery Redirect OnClick</title>
   </head>
<body>

<div style="margin:200px 200px;">
   <!--
      Here are our form elements,
      we have the select box / dropdown list
      which contains our URLs or links
   -->
   <select id="websites" style="width:200px;">
      <option value="http://demos.codeofaninja.com/tutorials/jQuery/get_dynamic_div_height.php">Get Dynamic</option>
      <option value="http://google.com">Google</option>
      <option value="https://codeofaninja.com">Blog</option>
      <option value="http://apple.com">Apple</option>
   </select>
 
   <!--
      And our buttons, the first one is "Open In Same Window"
      which opens the link selected on the dropdown in the same window.
     
      The other button is the "Open In New Tab" which opens the link in
      new tab (or window in safari)
   -->
   <input type="button" value="Open In Same Window" id="open_same_window" />
   <input type="button" value="Open In New Tab" id="open_new_tab" />
</div>

<!-- include our library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {

   //this will be triggered when the first button was clicked
   $("#open_same_window").click(function(){
      //this will find the selected website from the dropdown
      var go_to_url = $("#websites").find(":selected").val();
     
      //this will redirect us in same window
      document.location.href = go_to_url;
   });
 
   //this will be triggered when the second button was clicked
   $("#open_new_tab").click(function(){
      //this will find the selected website from the dropdown
      var go_to_url = $("#websites").find(":selected").val();
     
      //this will redirect us in new tab
      window.open(go_to_url, '_blank');
   });
 
});
</script>

</body>
</html>

Redirecting a page using JavaScript is fun. If you have any other techniques of doing this jQuery redirect onClick event, please drop it in the comments section below! Thanks!

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 Redirect onClick Event (New or Same Window)!