Tutorial: How to create a simple file or image management system with jQuery

Let me guess. The topic looks like a huge application that should be placed into a plugin instead of a tutorial? My reason is placing a system into a plugin will confuse yourself and your future programmers. Maintenance and future enhancement will kill you. I like things being kept simple and nice. So i write a tutorial for you instead. The end product can be seen below,
Simple-File-Management-System-with-jQuery_1247670298442

Problem

As always, if there is no problem i won't really write a tutorial. My problem was "I wanted a simple image management system but all i found was FTP application in Google". The basic idea was to have a simple management system for the existing user that had already logged into the system. Therefore, a FTP which required a username and password will definitely be OUT. I think about it and find it quite simple which roll me out to write out the application itself using jQuery

Requirement

This tutorial will require a fair bit of the following languages

  1. PHP
  2. jQuery
  3. JavaScript
  4. XHTML
  5. CSS

Definitely you will have to read a bit more but i try not to write too long to confuse you.

Concept

Let's start witht he concept of this simple application. The objective is to reuse and simplify the whole system without making the whole code look complicated and confusing for anyone to modify the code (i used to write 1 straight line of jQuery without needing to stop and found that i can't maintain my own code after sometime). So like MVC architecture pattern (ignore the MVC part if you want), we will need to split the structure, design and operation apart which connect to the server for communication. Simple to say we are splitting them as follow,

  1. Structure = HTML
  2. Design = CSS
  3. Operation = JavaScript & jQuery
  4. Server = PHP

Although it may be difficult but try to remember that anything that required to display for the first time will be file under structure and etc.

Let's roll out

Since i have already done the coding on my WordPress plugin and tested with it, i will just show you the coding and explain the reason for doing so. This section will be split into four sub section as what i have wrote on the concept section.

Structure

We will need to display all the images or files out of the folder that our user is going to manage. The following code will do just nice. Straight to the point.

<div id="body">
	<div id='frame'>
		<div id='container'>
<?php
		$path = getcwd()."/../random/";
		$files = glob($path.'/*');
		$files = array_filter($files, 'is_file');
		foreach($files as $file)
		{
			$file_name = basename($file);
			$url = $_SERVER["SERVER_NAME"]."/wp-content/demo/jQuery-file-management-system-how-to/random/".$file_name;
			echo "<div class='box'><img title='".$file_name."' src='".$url."'/></div>";
		}
?>
		</div>
	</div>
</div>

Please take note that all of the files contain in the folder are image. So once we have taken out all the files to display, now we will have to structure those pop out box for our user to perform action with the following codes.

<div class="navbox" id="navbox">
	<input type="button" class="hpt_rename" onclick="renameBox()"/>
	<input type="button" class="hpt_remove" onclick="deleteBox()"/>
	<input type="button" class="hpt_cancel" onclick="cancel()"/>
</div>
<div class="navbox" id="renamebox">
	<input type="input" id="input_rename" />
	<input type="button" class="hpt_rename" onclick="rename_confirm()"/>
	<input type="button" class="hpt_cancel" onclick="confirm_cancel()"/>
</div>
<div class="navbox" id="deletebox">
	<p>Are you sure?</p>
	<input type="button" class="hpt_remove" onclick="delete_confirm()"/>
	<input type="button" class="hpt_cancel" onclick="confirm_cancel()"/>
</div>
<div class="navbox" id="messagebox">
	<p id="errormsg"></p>
	<input type="button" class="hpt_retry" onclick="retry()"/>
	<input type="button" class="hpt_cancel" onclick="confirm_cancel()"/>
</div>
<div class="navbox" id="okbox">
	<p id="okmsg"></p>
	<input type="button" class="hpt_ok" onclick="hideAllBox();appear();"/>
</div>

What we have here?

  1. Navigation pop out box structure
  2. Rename pop out box structure
  3. Delete pop out box structure
  4. Error message box pop out structure
  5. OK pop out box structure

So the structure is being placed here instead of dynamically writing them out using jQuery since it is not required to be dynamically we do not want to add in complexity into the always complex JavaScript. And that is all for the structure!

Design

Let's style the structure a bit to give them a little bit of effect for the end user. The very basic part will be to style the overall alignment of the display.

body
{
	margin: 0 auto;
	text-align: center;
}
#frame
{
	width: 90%;
	margin: 0 auto;
	text-align: center;
	padding: 2em;
}
.box
{
	float: left;
	border: #CCC solid 1px;
	padding: 1.5em;
}

.box:hover {
background: #CCC;
cursor: pointer;
}
  1. all element of the body to center
  2. set the frame width and align to center
  3. each element in the frame will float against another
  4. on hover effect for each box of image

This is all we need to style the basic structure! Next the pop out box!

.navbox
{
	background: #FFF;
	width: 220px;
	height: 110px;
	padding: 1em;
	border: #CCC solid 1px;
	position: absolute;
	z-index:2;
	cursor: pointer;
	text-align:center;
	margin: auto;
	left:50%; 
	top:50%; 
	margin-left:-110px;
	margin-top:-55px;
	display:none;
}
input
{
	width: 100px;
	height: 50px;
	border: 0;
	cursor: pointer;
	text-align:left;
}
.hpt_rename
{
	background: transparent url('../images/rename.png');
}
.hpt_remove
{
	background: transparent url('../images/remove.png');
}
.hpt_cancel
{
	background: transparent url('../images/cancel.png');
}
.hpt_retry
{
	background: transparent url('../images/retry.png');
}
.hpt_ok
{
	background: transparent url('../images/ok.png');
}
#input_rename
{
display: block;
width: 200px;
border: #CCC solid 1px;
}

Basically the above code just assign each image to the respective button and align the pop out box at the center. That's all the important thing to know!

Operation

JavaScript and jQuery code are next. There will be a lot of methods but each method will be quite short to promote reusability. Short and clean. Initially, we will have to assign an event handler for each element on the screen with the following code.

var currentObj = null;
var fail = '';
jQuery(document).ready(function() {
	attach_handler();
});
function attach_handler()
{
	$('.box').click(function(){
		currentObj = this;
		$('#body').css({"position":"absolute", "z-index": "1", "top":0,"left":0,"overflow":"hidden","background":"#000"}).animate({opacity: 0.3},500, function(){$('#navbox').css("display", "block");});
		window.scrollTo(0,0);
	});
}

The method attach_handler() is really easy to understand. In term of English, the statement is saying that each element in the image will have a handler that assign its object to 'currentObj' for future references, turn the screen to black and display the navigation box. Finally, scroll it up to the top of the screen. The fail variable if used to verify which action has fail.

Now, notice that each button has an event handler on the structural part which will be passed into the following methods

function cancel()
{
	hideAllBox();
	appear();
}
function appear()
{
	$('#body').css({"overflow":"visible", "position":"absolute", "z-index": "0", "background":"#FFF"}).animate({"opacity": 1},1000);
}
function renameBox()
{
	hideAllBox();
	$('#renamebox').css("display", "block");
}
function deleteBox()
{
	hideAllBox();
	$('#deletebox').css("display", "block");
}
function messagebox()
{
	hideAllBox();
	$('#messagebox').css("display", "block");
}
function okbox()
{
	hideAllBox();
	$('#okbox').css("display", "block");
}
function hideAllBox()
{
	$('#renamebox').css("display", "none");
	$('#deletebox').css("display", "none");
	$('#messagebox').css("display", "none");
	$('#navbox').css("display", "none");
	$('#okbox').css("display", "none");
}

What does the above small little methods do? Display and Hide the box accordingly! Short and sweet? But the main important part is actually the appear method that i would need to explain. It is doing the opposite of what the each element action handler does. It make the pop out box disappear instead of appearing. (appear as in appearance of the screen)

Next are the confirmation buttons and retry button.

function getSelectedFileName()
{
	oldname =  $(currentObj).children('img')[0];
	oldname = $(oldname).attr('title');
		return oldname;
}
function delete_confirm()
{
	filename = getSelectedFileName();
	ajaxCall('D', filename,'');
	
}
function rename_confirm()
{
	var available = true;
	var newname = $('#input_rename').attr("value");
	var rename = document.getElementById('input_rename');
	if(isAllowedName(rename,"Found Invalid Character! Rename Failed. Only symbol '-' or '_' allowed"))
	{
		$('#body').contents().find('img').each(function(){
		oldname = $(this).attr('title').split(".");

		if((oldname[0]).toLowerCase() == newname.toLowerCase())
		{
			available=false;
			return;
		}
		});
		if(available)
		{
			oldname = getSelectedFileName();
			ajaxCall('R', oldname,newname);
		}
		else
			alert("The name has been taken. Please choose another name");
	}
}
function retry()
{
	fail == 'D'?delete_confirm():rename_confirm();
}

First! Notice we used fail variable in retry()? This is the global variable we first declare on the top of the screen. The two other confirmation are delete and rename. delete is straight forward. Get the file name of the object ( which is why each event handler has to identify themselves to the global variable ) and send them through to the server request method. Rename will required more validation to be done since it is a textbox. But after validation checking we will also do the same as the delete function (send in the request).

Next. The Ajax function and validation methods. But let's start with validation method.

function isAllowedName(elem, helperMsg){
	var alphaExp = /^[-_0-9a-zA-Z]+$/;
	if(elem.value.toLowerCase().match(alphaExp)){
		return true;
	}else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}

regular expression to check for valid character and symbols allowed etc. and display a message if it fail. return true or false. Normal validation procedure (notice space is not allowed). Now we go to the longest codes in the whole script (47 line?), the ajax function.

function ajaxCall(caller, nameold, namenew)
{
	$.post("hpt_operate.php", { op: caller, oldname: nameold, newname: namenew }, function(data){
		if(caller=='D')
		{
			if(data == "1")
			{
				
				$("#okmsg").html("Delete Successful");
				$(currentObj).remove();
				okbox();
				
			}
			else
			{
				fail = 'D';
				$("#errormsg").html("Delete has fail, Please try again later or contact <a href='[email protected]'>Clay</a>");
				messagebox();
			}
		}
		else if(caller=='R')
		{
			data = data.split("||");
			if(data[1] == "1")
			{
				$("#okmsg").html("Rename Successful");
				var domain = 'http://' + window.location.hostname + '/wp-content/plugins/hungred-post-thumbnail/images/random/'+data[0];
				$(currentObj).parent().append("<div class='box'><img title='"+data[0]+"' src='"+domain+"'/></div>");
				$('#input_rename').attr('value','');
				$(currentObj).attr('title', namenew);
				$(currentObj).remove();
				$('.box').click(function(){
					currentObj = this;
					$('#body').css({"position":"absolute", "z-index": "1", "top":0,"left":0,"overflow":"hidden","background":"#000"}).animate({opacity: 0.3},500, function(){$('#navbox').css("display", "block");});
					window.scrollTo(0,0);
				});
				okbox();
				
			}
			else
			{
				fail = 'R';
				$("#errormsg").html(data);
				messagebox();
			}
		}
  });
}

This does look long. jQuery post method. Really easy to use and everything has been done for us in this quick and easy method provided by jQuery. We just pass the name of our server script and the data required and off the request goes. The troublesome thing is when the data came back. For delete, we do checking for success or failure and prompt the correct ok/message box respectively. Rename does the same thing but like delete it will have to remove the element and insert them back to the structure to ensure the changes really has done correctly by the server (we can just rename the src and title but it won't work on all browser). Finally, we will react the event handler since the new member do not have its own event yet. Look at the code written for rename, additional complexity appended into the script compare to structured them outside the script. (imagine if we add all the DOM manipulation in the script, the tutorial will become hell).

Anyway, notice that every single method mention above was used at least once and the number of instructed used for each method was only a few lines. This means that any new features should also reuse these methods to avoid whole chunk of codes and redundancy. Remember we write for human not for computer.

Server

Lastly, the instruction to handle the Ajax request are as follows,

$op = make_safe($_POST['op']);
$oldname = make_safe($_POST['oldname']);
$newname = make_safe(preg_replace("/[^a-zA-Z0-9\s-_ ]/", "",  $_POST['newname']));

$path = getcwd()."/random/";
$extension = explode(".", $oldname);
$extension = $extension[1];
if($op == "D")
{
	echo unlink($realpath);
}
else if($op == "R")
{
	echo $newname.".".$extension."||";
	if(file_exists($path.$newname.".".$extension) == false)
	{
		echo rename($path. $oldname, $path.$newname.".".$extension);
	}
	else
		echo "File Exist, Rename Fail. Please use a different file name";
}

function make_safe($variable) {
	$variable = htmlspecialchars(htmlentities(trim($variable)));
	return $variable;
}

Since we provide a text box basic filtering will be required. Thus, make_safe was created. The above code should also have speak for itself. Anything you don't understand shoot me a question.

Demo

Finally the demo. For most of the codes above i did not change the name which was used in my WordPress plugin. Therefore you will still see same bit and pieces of my plugin prefix. You can find the demo at simple image management system with jQuery but delete has been removed (we won't want the next visited to see nothing on the demo). The files for this demo can be found at jQuery-file-management-system-how-to (without images). Each method comment is written in the attached file (not in the tutorial) to avoid the number of words which make you bored.

Conclusion

Currently this is not a fully released of the system and many possibility can be implement or inserted into this code. But I find that this really isn't much of a tutorial but a way to show you that writing codes in another way do make a differences in term of maintenance, readability, usability and etc. etc. Especially when you are writing a Open Source code to share. Hope you enjoy this!

Tutorial: How to validate whether a user has logged into WordPress

Since i can't find this information anywhere on Google and WordPress search box, i will write a post out to save time for people who want to validate whether a person has logged into WordPress to access their external plugin page (another page that is not resist in WordPress Administrator panel).

Problem

My plugin has a file mangement page that help manage the site images from my plugin but the page was external and could be access by ANYONE as long as they have the URL, this is not secure at all. Thus, i wanted to know whether WordPress has any method or action hook that allow to validate a user upon entering that page. I tried Google and WordPress search box for any open question for this. Unfortunately, there isn't any.

Solution

In order to use methods exist in WordPress in an external page, we will have to include them into your page. The file i used to include in my page was 'wp-config.php' in WordPress. This will include all WordPress methods and dependency that these methods have so we won't have to worry that our plugin will just break suddenly.

The other important thing after the main page has been imported is the method. WordPress provides a method called 'is_user_logged_in()', with this method, we can validate whether that particular user has logged into WordPress to check whether they are the correct user. The following code illustrate the above explanation,

require_once '../../../../wp-config.php';
if ( is_user_logged_in() ) 
{
	echo "i am logged in";
}

This is jusst a demo so the real code of mine won't be here to confuse you. The require_once path used is just to navigate downwards. So any user of WordPress can access the page? Of course not! Using the following code we can validate which level of access the user has,

require_once '../../../../wp-config.php';
global $current_user;
get_currentuserinfo();
$level = $current_user->user_level;
if ( is_user_logged_in() && $level == "10") 
	echo "you have access";
else
	echo "you do not have access";

This way we will have to validate what access level this particular user has with the global variable $userdata, WordPress doc has demonstrate this pretty nicely and by checking its access level, you can restrict what level of user is allowed to access your page.

Tutorial: How to align center on the screen when using position absolute with CSS

As a developer, i always have the chance to come across position: absolute when doing layout and dynamic animation such as pop out box and etc. But for many years it seems like until today then i realize how to correctly align an absolute position container on the center of the screen. Many tutorial uses many trick in order to position their container on the center of the screen for either alert or selective option but it is really REALLY easy to align your container on the center when using position absolute. I will try to show you some simple and easy way to do this with little complication (The reason why it is difficult are mostly because there are so much words written on some tutorial that make it hell confusing).

Align center of the screen

In order to align your container to the center of the screen, what you need is only the following code.

margin: auto;
left:0; right:0;
top:0; bottom:0;

That's all! Simple and easy to use. We usually use the following to align to center

margin: 0 auto;

This is when we are not using position absolute but this is actually the correct way to align horizontally when using position absolute too! But there is a criteria when we try to align it horizontally using the above code, left and right. We have to reset the right and left in order for the browser to render it to horizontal center with the above code. For vertical center alignment, we will have to reset the top and bottom part. And use the below code to render vertically but not horizontally.

margin: auto 0;

Sound logical right? To sum it up to align horizontally and vertically, we will use the first code that was presented in this article which reset four side and set auto for margin (so that it automatic align for the four side)

Demo

Simple and quick demo to show you that the above code work. Below is the CSS used in the demo

body
{
	text-align: center;
	margin: 0 auto;
}
#box
{
	margin: auto;
	left:0; right:0;
	top:0; bottom:0;
	position: absolute;
	width: 200px;
	height: 200px;
	border: #000 solid 1px;
	background: #82713F;
	text-align: center;

}

The HTML is just a div box

<div id="box"></div>

You can visit the demo at align center of the screen when using position absolute

P.S: This work in all browser except IE

Method that work for all browser

There is a simpler method that will work in ALL browser. But it will required you to know your own block size (the container width and height). It's really just maths, for example, you have a container with a width of 60% and height of 40%, you will want to move your container 20% from its position to the right (assuming it is at coordinate 0,0) and 30% from top to bottom. Why 20%? Because we must balance between the left and right side of your 60% width container, so 100-60=40/2=20%! Same thing goes for your height. With these condition applied, i can show you the demo with the following code.

body
{
	text-align: center;
	margin: 0 auto;
}
#box
{
	position: absolute;
	width: 60%;
	height: 40%;
	left: 20%;
	top: 30%;
	border: #000 solid 1px;
	background: #82713F;
}

And the HTML part will be the same as our previous demo, you can view the result with different browser at align center of the screen when using position absolute with all browser

Another method also similar to the above but it uses another concept. Instead of calculating the right and left side of the width required in percentage, we use the known width and height which usually locate at coordinate (0,0) and push it opposite direction after we request the CSS to move to center by left and top to 50%. Talk won't help explain as much as example, with the following code it will illustrate better,

body
{
	text-align: center;
	margin: 0 auto;
}
#box
{
	position: absolute;
	width: 500px;
	height: 500px;
	left: 50%;
	top: 50%;
	margin-left: -250px;
	margin-top: -250px;

	border: #000 solid 1px;
	background: #82713F;
}

What the above does is giving it a fixed width and height (500px), push it to 50% from left to right and top to bottom. It will not align on the center with just this, we will have to use margin to push in the opposite direction(-250px) by half in order for it to align to center. You can look at the result at align center of the screen when using position absolute with all browser compatibility

Avoid trouble with filter and the_content in WordPress

One problem i just came across while working on my WordPress plugin that many might not know is the danger of making mistakes on filter and the_content action hook. The importance of 'the_content' action hook and where this particular small sentence will affect your overall WordPress and caused it to malfunction if WordPress plugin developer used it carelessly (scary stuff). In this article, i will show you some of the mistake i made and what are the consequences in screen shot to inform WordPress plugin developers what will happen to WordPress when this two is being used wrongly.

What is 'the_content and filter?

In case you don't know what is filter and the_content action hook, filter is used in WordPress to filter the data between WordPress and its database. Short to say, you can manipulate the data retrieved from WordPress database before it shows out. The 'the_content' action hook is used to tell WordPress to print the content of the post, short to say, i am trying to manipulate the data from WordPress before displaying out to the end-user.

Problem

i have a test site which use to debug and test my plugin in a test environment before implementing it on the LIVE site. Everything goes well on the TEST since there is only one plugin but problem came when there are more than one plugin which hell can happen, not only deal to naming or method contradiction but some other unknown problem can occurred. One of the very rarely unforeseen problem is the filter and 'the_content' action hook problem. By the way, I am using WordPress v2.8 for testing.

Consequences

Many might not know what will 'the_content' affect the internal and external of WordPress (Many might aware of the external consequences but not the internal ones). Let's take a look at one of my plugin tester site (http://1sitedaily.com) who reported these problems to me. In the post page, she was typing the post and this particular red thing came out of no where!
unidentify-red-bar-wp

This red post was either the previous post or the current post! It was caused by the use of 'the_content' action hook imappropriately (imagine how irritating will it be for the user). Once she clicked save as draft or worst when it suddenly auto save as draft and empty page is return!

post-save-draft-empty

Although the page was saved, this is not acceptable! Internally, this is what will happen to the Administration panel when 'the_content' action hook is not being used appropriately. Nonetheless, if this method is not used appropriately for the external part, the content might not even be showing!

missing-front-panel-content

This has missing content on the front page.

missing-sing-page-content

Same post with missing content on single page.

What happen?

So what really happen there? It is actually quite a silly mistake make by developers with PHP (even me) that usually forgotten by them when writing for a open source application. Deep in our mind, we think this is a new language with all the rule define by WordPress but its actually just PHP.The external mistakes was,

function article_example($content)
{
	if($content != "")
	{
		echo $content;
	}
	else
	{
		echo "NOTHING FOUND";
	}
}
add_filter('the_content', 'article_example');

Nothing seems wrong here, right? It will print out the relevant codes instructed on the template. But this is where the problem comes internally. Since filter event handler is also attached in the administration panel, anything that trigger 'the_content' in the administration panel will result in the above function execution (this means post page also uses 'the_content' to output the display we see on the editor). So, the red box appeared in WordPress was due to Ajax function being executed behind WordPress to save as draft and the function above was executed which duplicated a content out of the post. When the 'save as draft' button was clicked, a empty page (or any other words in the page which does not return the user back to the post page) was returned because the above function was executed and the echo statement was called. In PHP, during any execution or redirection was occurring, and echo statement will stop the page from redirecting. That is the main reason why the post page was not shown and other page appeared in front of the user.

The internal mistakes are something like this,

function article_example($content)
{
	$content = "The content contains: ".$content;
}
add_filter('the_content', 'article_example');

which the developers forgotten to output or return the correct value back to WordPress. The other thing that might occurs will be semantic errors or logic error.

Correct way of displaying filter and 'the_content'

Save yourself some time, in WordPress to echo a statement when using the filter statement ALWAYS use return,

function article_example($content)
{
	return "The content contains: ".$content;
}
 add_filter('the_content', 'article_example');

returning the value using filter will also resulting the display of the modified content! No problem will occurs like the above one when using return instead of echo although it also do the job!

Tutorial: How to create a simple vibration effect for your form box with jQuery

This effect can be used to validate certain criteria in your form. Other than using highlighter to highlight the error area, we can use a more creativity approach by vibrating that particular input box to alert the user. This tutorial demonstrate a very easy way to understanding how vibration works on the web and how it can be used in your web design.

The Concept

In order to perform a vibration effect, we must first understand how will a person feel during an earthquake. The whole world will be shaking right? In a more defined term, it means that the object are moving on it own, not us. Similarly, we are staring at the monitor while the boxes are moving on its own! Next question, how do you move? The answer to my question will be the same answer on how the boxes move but not by legs. Rather, the position will be moved. In conclusion, we will try to move the position left and right, up and down to simulate vibration.

The Code

Coding part will be split into 2 part. The structural and jQuery part. The CSS part is fairly simply to understand since we are just aligning them to the center and that's it.

HTML

The following will be the only thing we need in here.

<div id="frame">
	<div id="container">
		<div class="box" id="box1">
		<p>Username<input type='text' size='20'></p>
		<p>Password<input type='text' size='20'></p>
		<p><input type='button' value='Submit' id='activate'/></p>
		</div>
	</div>
</div>

We will only use the 'frame' and 'activate' ID in this tutorial. You can safely ignore all other structure as it will not affect the vibration. The reason is we are shaking the most outer box which is 'frame' and an event handler is attached on 'activate'.

jQuery

The confusing part may be the jQuery code. But we will only need to know certain variable in order for this to work. The variables are,

  var interval = 30;
  var duration= 1000;
  var shake= 3;
  var vibrateIndex = 0;
  var selector = $('#frame');
  var stopVibration;
  var vibrate;

Let me explain the variable shown above in a well indented manner,

  • interval: this is used to set the duration for each movement. eg, every 30 millisecond it will move left,right,top or bottom once.
  • duration: this is used to set the duration for the whole effect. eg, it will vibrate for 1000 millisecond
  • selector: this is the jQuery selector we are going to apply the vibrate with
  • stopVibration: this is the method that will stop the vibration after 'duration' variable
  • vibrate: this is the method that will start the vibration
  • vibrateIndex: this is the index that setInterval provides when used to tell 'stopVibration' which vibration to stop

It should be easy to understand the variables needed for this effect to accomplished. Now for the 'stopVibration' and 'vibrate' method explanation:

	var vibrate = function(){
	$(selector).stop(true,false)
	.css({position: 'relative', 
	left: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px', 
	top: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px'});
	}

Let's start with 'vibrate'. The above code will take the selector and stop whatever animate it is performing and set the box position as relative so it will move starting from his original position. We set the left and top randomly with a mathematics calculation. So it will move itself left or top randomly. (change the equation to make it vibrate differently)

	var stopVibration = function() {
	clearInterval(vibrateIndex);
	$(selector).stop(true,false)
		.css({position: 'static', left: '0px', top: '0px'});
	};

'stopVibration' will stop the interval with the index given and return the box to its original position. That's it!

Lastly, we will need to add an event handler to the button for it to vibrate!

	$('#activate').click(
	function(){	
	vibrateIndex = setInterval(vibrate, interval);
	setTimeout(stopVibration, duration);
	});

The button click will be attached with an event handler click that will use setInterval to vibrate the outer container in every 'interval' given (move left right top down randomly in every 'interval'). This will caused it to vibrate forever. Thus, we will have to use 'setTimeout' function to stop the vibration by placing the method 'stopVibration' and the 'duration' it wants to vibrate. And it is as simple as that. The final code will be:

$(function() {
  var interval = 30;
  var duration= 1000;
  var shake= 3;
  var vibrateIndex = 0;
  var selector = $('#frame');
	$('#activate').click(
	function(){	
	vibrateIndex = setInterval(vibrate, interval);
	setTimeout(stopVibration, duration);
	});

	var vibrate = function(){
	$(selector).stop(true,false)
	.css({position: 'relative', 
	left: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px', 
	top: Math.round(Math.random() * shake) - ((shake + 1) / 2) +'px'});
	}
	
	var stopVibration = function() {
	clearInterval(vibrateIndex);
	$(selector).stop(true,false)
		.css({position: 'static', left: '0px', top: '0px'});
	};

});

That is all you need to make your own vibrate effect.

The Demo

You can get and view the demo files from the following link: