Ways to debug your jQuery or JavaScript codes

Debugging your client code is rather a normal procedures for any web developers. Everyone will shout Firebug! yeah, me too. But Firebug is great for syntax detection but how about logic problem? In this article i will share with you some of the ways i used to debug my JavaScript or jQuery codes when I'm developing my web application. I will also share with you a trick that i used on my code to alert me that a bug occurs in a particular script since i don't get many helpful users nowadays.

Alert Them Out

The most simple and basic way of debugging is by using JavaScript alert function. This is old but is quite useful sometimes. Especially when you do not want to remember other debugging methods. It's pretty simple, alert the message you want to see. If the alert doesn't appear, this means that the error is before the alert statement. I usually do this when I'm debugging IE although there are tools available for IE.

alert("The Bug Is Somewhere Before ME!")

Log them up

Well, if you are using WebKit browsers for your development (FireFox, Chrome, Safari) you may want to try this.

if (window.console)
  window.console.log("The Bug is killing me");

What this does is to log the string 'The Bug is killing me' into the console such as Firebug. It's always better than using alert and see this infinity loop that keep popping out until you are force to shut down your browser!

Log them with jQuery

The above two methods work both in jQuery and JavaScript. But this only function well in jQuery. This is definitely not something i came up with but its from Dominic Mitchell

  jQuery.fn.log = function (msg) {
      console.log("%s: %o", msg, this);
      return this;
  };

The above creates a function, 'log'. This function will do exactly similar to the one above but the differences is that it format the string a little bit before displaying out to the console. This is good for debugging your long chaining with jQuery. Although the previous method also can be used to debug chaining but it will required an additional line instead of including it into the chaining process. So you can debug this way,

  $(root).find('li.source > input:checkbox').log("sources to uncheck").removeAttr("checked");

Try and catch

In JavaScript, you can try to catch the error in a particular scope. This way, it won't propagate to other section of the code.

try
  {
  //Run some code here
  }
catch(err)
  {
  //Handle errors here
  }

This is pretty good when you are trying to debug one of the many function in your JavaScript.

Catch them all

The last one i am going to show you is to catch any one of the error into a particular function instead of using multiple try and catch.

function handleError(e)
{
alert(’An error has occurred!\n’+e);
return true;
}
window.onerror = handleError;

This will handle any error occurs in your JavaScript code to the function 'handleError'. You will want to use this at the end of your script. Especially if you want to be informed whether a particular function or script has malfunction and the users are not reporting. Basically, what you can do is to gather all information and placed them into a String or JSON. Using ajax to delivery these information to your email or database. This way, your support team will have an idea which part are having problems and your system will be more reliable. (testing doesn't means 100% bug free) The information that you may want to know are usually located at Navigator Object in JavaScript.

Summary

These are the methods i usually look at when debugging my own client script. It might not be everything but i hope it can be useful to some of you out there. Hope you learn something!

Tutorial: How to make your own simple and nice Slider with jQuery Part 2

In my previous tutorial on how to create a Slider with jQuery, i illustrated the concept to build up an jQuery Slider easily with a few line of jQuery code and an explanation on how it is being done. But in my previous article, it doesn't work as perfectly as this one since our objective is to provide an understanding on how it work. In this article, i will bring out the fully workable version of my previous article. Short to say, this article will contains more information on why the previous one doesn't work as well as what has been found and solved.

Requirement

Before i start this short article (hopefully) there is some requirement that i wish you could follow before proceeding to read further.

  1. Read the previous tutorial on Slider with jQuery because in this article i won't repeat much on the concept and how it is being done!
  2. Have basic knowledge of HTML, jQuery and CSS
  3. Wish to construct a workable jQuery Slider on your own instead of just understanding how it work

The Problem

There are a few things i came across when working on a jQuery Slider from my previous article.

  1. The scroller doesn't stop when the user mouse up sometimes
  2. jQuery doesn't support sequence event trigger: means it cannot prioritize which event should trigger when an element has multiple events
  3. The mouse will always pull to the starting line of the scroller

This is as far as i remember for what happen between the current and the later version differences. Although both work quite well.

The Solution

The CSS and HTML are perfectly the same! The only differences occurred on the jQuery codes and below listed what has been done to eliminate the above issues and the final code in jQuery.

  1. The mouseup event handler was embedded within mousemove event handler. This means that mousemove must first initialize before mouseup will be triggered which is not always the case. Thus, the two event handler were seperated.
  2. Since jQuery doesn't support priority event triggering, i used a boolean variable to stop the movement and wait for mousedown event to complete before it can start the other instruction within the mousemove event. This will solve the problem where mousemove initialize first before the distance between the scroller and starting point being calculated in mousedown event.
  3. The reason why it always pull to the starting line was because it was instructed to do so. I did not calculate the disance between the scroller and starting point which is required to tell the program to start at any point occurs within the scroll bar!

The above explanation might not help you understand a single bit at all! But the below code will definitely assist you in relating the explanation above.

$(function(){
	var myoffset = $('#scroller').offset();
	var myxpos = parseInt(myoffset.left); 
	var width = parseInt($('#scrollbar').css('width')) - 196;
	var action = false;
	var startpos = 0;
	var move = 0;
	var scroller = 0;
	
	$().mousemove(function(e){
		move = parseInt(e.pageX-myxpos);
		$('#scroller').mousedown(function(){	
			action = true;
			scroller = parseInt($('#scroller').offset().left);
			startpos = move - (scroller - myxpos);
		})
		if(action)
		{
			move = move - startpos;
			if(move < = 0)
				move =0;
			if(move >= width)
				move = width;
			if(action)
				$('#scroller').css('left', (move)+'px');
		}
	})
		$('*').mouseup(function(){
			action = false;
		});

});

Let's see how do i explain this. Let's do it in point form similar to the problem we have.

  1. Notice '$('*').mouseup(function(){...' was placed outside instead
  2. Notice 'if(action)......' was there to stop all instruction from initializing before '$('#scroller').mousedown(function(){..' completed'
  3. Notice '$('#scroller').mousedown(function(){ ....' contains variables 'scroller' and 'startpos'

I think this will clear out what my messy explanation has just caused. After these three has placed up, you will have a full and nice version of jQuery Slider from my previous article.

The Demo

It will be pretty confusing whether there is really a full version of jQuery Slider without using a jQuery Plugin. Thus, i have prepare two demo for you. The first one is the understanding demo and the other one is the current full version demo!

Tutorial: Simple grey out screen effect with jQuery

Grey out screen is done previous in JavaScript. But jQuery has became so powerful in reducing the number of codes required that makes me wanted to try how well this can be done using it. Personally, i wanted to check out how easy it is to create a grey out screen with a pop out box at the center of the screen. This is purely for the sake of exploring and experiencing how simple can a grey out screen be done in jQuery.

The Objective

The objective of this article is to produce a simple grey out screen effect in jQuery with the minimum amount of code required. Of course, this is just the goal. But let's see how simple and easy this can be done with minimum amount of codes and maximum completeness.

The Requirement

Here are the following requirement for this simple tutorial

  • Basic CSS, HTML, jQuery Knowledge
  • Read what is written!

Although it is obvious, but usually people tend to skip the second requirement.

The Concept

Let's imagine the body tag (also known as <body>) is the curtain and the box is the person who will appear when the curtain is closed. If the box is in the body when the curtain is closed, we won't be able to see the box!(you will see no person out on the front when the curtain closed). Furthermore, if we grey out the body tag the background of the page will change to black instead of grey which is not what we want. Therefore, the grey out screen should be placed as a standalone curtain just below the body tag (children of <body>). Normally, we will usually assume when the screen is grey out, all the child within the screen will also be grey out and those that are outside are unaffected. Unfortunately, this is not the case. It may surprise you but any element in the screen will be display instead! eg. anchor or hyperlink. Thus, if you want your element to be untouchable after grey out effect, it is best to placed grey out screen as standalone!

The Code

The code will be split into three part, HTML, CSS and jQuery. There will be more explanation than codes since we will want to understand what is going on in the code and the code is suppose to be MINIMUM

HTML

We will need three things in this article. They are 'box', 'screen' and 'button'.

	<input type='button' value='grey out me!' id='button'/>
	
	<div id='box'>
	</div>
	
	<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
	
	<div id='screen'>
	</div>

And finally a lot of break to make the page long enough to detect a problem later on. The elements are describe below,

  • box: the pop out box after screen grey out
  • button: the button that will initialize screen grey out
  • screen: the screen that will cover the whole page grey!

CSS

Well, on the CSS part we will style the 'box' and 'screen' only!

#box
{
	width: 150px;
	height: 150px;
	background: #FFF;
	border: red dotted 5px;
	text-align: center;
	position: absolute;
	margin-left: -75px;
	margin-top: -75px;
	left: 50%;
	top: 50%;
	z-index: 20;
	display: none;
}

#screen
{
	position: absolute;
	left: 0;
	top: 0;
	background: #000;
}

These can be placed in jQuery code instead but since we want it to render faster, placing them in CSS will be a much better option(It really depend on you). Let me explain the 'box' CSS first.

  1. Give 'box' a width, height, background color and border so that it is visible on the screen
  2. align 'box' to center
  3. position it as absolute and make it visible(z-index) even when the screen is grey out
  4. margin-left/top,top,left are to align it on the center of the screen (cross browser) but in a fixed way
  5. we hide it (the display)

The 'screen' CSS is fairly easy to understand. We have to position it as absolute and align it at the top left hand corner so that it will cover the entire screen!

jQuery

Above section should be quite clear and simple. But, the jQuery code is even easier to understand.

$(function(){
var pop = function(){
	$('#screen').css({ opacity: 0.7, 'width':$(document).width(),'height':$(document).height()});
	$('body').css({'overflow':'hidden'});
	$('#box').css({'display': 'block'});
}
$('#button').click(pop);
});

The above should be quite basic. But the explanation are listed below,

  1. 'var pop = function(){..' wait until jQuery is ready!
  2. 'var pop = function(){..' create a function name 'pop'
  3. '$('#button').click(pop);..' attach an event handler, click onto the button
  4. '$('#screen').css({ opacity: 0.7, "w....' function activate we grey out the screen by providing the 'html' or 'page' width and height (instead of box size). This will cover the whole screen.
  5. '$('body').css({"overflow":"hidden"});' this is to fix the problem of using a 'fixed' center align CSS declaration
  6. '$('#box').css({"display": "block"});' this is to make the box appear!

It is really that easy! But going into grey out mode is simple, how about returning back to normal? Definitely, an extra event handler is required on the 'box' to reverse back the procedure!

$(function(){
var pop = function(){
	$('#screen').css({'display': 'block', opacity: 0.7, 'width':$(document).width(),'height':$(document).height()});
	$('body').css({'overflow':'hidden'});
	$('#box').css({'display': 'block'}).click(function(){$(this).css('display', 'none');$('#screen').css('display', 'none')});
}
$('#button').click(pop);
});

I have just added two things above, can you identify them?

The Demo

The above demo and files can be viewed from the following link.

Wait!

I'm not done (nagging)! If you notice, i made a cheat on top to simplify the overall complexity. And the cheat is 'overflow: hidden' on the jQuery code. But not all browser support this! How about those that doesn't?! This is where i add in additional component so that we do not have to even rely on 'overflow:hidden'!

The Problem And Solution

The problem with the above grey out screen effect was due to the 'box' (the cheat was for 'box' too). remained at the same position when we are scrolling which is a big NO NO. Therefore, we can either make the box to align fixed at the center or move along while the user scroll (persistence box). We have illustrated the cheat for screen grey out effect using jQuery. Now we will do the second one, the persistence box.

The Persistence Box

The answer to persistence box is located at Align center of the screen while scrolling with css What we have to do here is to change the CSS 'box' position: absolute to position: fixed. Of course, we will have to remove the overflow: hidden on the jQuery statement. This will make it chase after your scroller and urge your users to take action on the 'box'. The final CSS code will look like this,

#box
{
	width: 150px;
	height: 150px;
	background: #FFF;
	border: red dotted 5px;
	text-align: center;
	position: fixed;
	margin-left: -75px;
	margin-top: -75px;
	left: 50%;
	top: 50%;
	z-index: 20;
	display: none;
}

And we will remove overflow: hidden in jQuery and the final code will look like this,

$(function(){
var pop = function(){
	$('#screen').css({ opacity: 0.7, 'width':$(document).width(),'height':$(document).height()});
	$('#box').css({'display': 'block'});
}
$('#button').click(pop);
});

This look even shorter than the previous one! Finally, we get a complete screen grey out effect in it simplest form.

Update 25 September 2009****
Matt asked a very good question below, this method will caused the grey out box stuck due to the css being set to 'fixed'. Hence, minimize to maximum in window browser will caused the grey out to stuck at the minimize size. Here is one of the solution you can live with.

$(function(){
var pop = function(){
	$('#screen').css({	"display": "block", opacity: 0.7, "width":$(document).width(),"height":$(document).height()});
	$('#box').css({"display": "block"}).click(function(){$(this).css("display", "none");$('#screen').css("display", "none")});
}
$('#button').click(pop);
$(window).resize(function(){
	$('#box').css("display") == 'block'?pop.call($('#button')):"";
});
});

I added an event handler during resize, check whether the box is displayed and it was displaying during resize we overwrite the pop out box again. The demo page was also updated for this update.

Demo for persistence box

The demo can be viewed on the following link!

Tutorial: How to make your own simple and nice Slider with jQuery

Well, this is not new and can be easily found on jQuery UI but you will have to download jQuery UI and use it as if it is a plugin. But for my case, i wanted to find out and construct an easy and nice slider for myself. Many will skip this step and use jQuery UI instead. But when it come to customization for vertical slider, it may come to a good use for developers or even designers to know how this is being made (you can look into the code of a plugin but it will definitely take more time).

The Problem

I am currently building a gallery similar to the current Slider Gallery plugin. But i wish to know how slider can be achieve easily without using the existing plugin or library (learning purpose). The gallery can have vertical or horizontal slider and customize the outlook to my personal need.

The Solution

I can use the existing jQuery plugin or study them to construct a jQuery slider easily. But plugin codes contain many DOM manipulation to construct HTML structure automatic in order to ease the job needed for developers or designers. In return, we eliminated the efficiency of the website because of the extra codes required in the plugin to do things automatically. Personally, i will prefer something simple and easy to understand for future enhancement and maintenance by myself (i believe majority developers or designers will love simple stuff to work with). Thus, i brainstorm something similar to a slider which might not have the same concept as jQuery UI (i never actually look at it) but should be around the same.

The Concept

Before we go into the actual coding, i like to write a small concept out for myself to understand this in the future. Basically, we need two things in a slider, the scroller and scroll bar. But this two things are not enough. There is a need for an outer container to place these two. Why? Because we need to align both scroll and scroll bar together. Therefore, both the scroller and scroll bar will have to be position in absolute. The most outer container will be position relative to prevent the absolute positioned containers from getting out of the constraint area. So we will have something as shown below,
illustrate
In order to move it accordingly, we will move the variable 'left' since the scroller is positioned absolute and use variable 'top' if we are moving vertically.

The Code

The code will be split to three part, HTML, CSS and jQuery. This is best to simplify the overall concept.

HTML

The HTML code is fairly simple and straight forward. We will create the three container which were mention on the concept section as shown below,

	<div id="scrollcontainer">
		<div id="scrollbar">
		</div>
		<div id="scroller">
		</div>
	</div>

i have placed the id for each container so that we can manipulate them when we come to jQuery coding. Short and clear.

CSS

In the CSS, this play a much bigger role as most of the display is done in here. For the outer container we will just need it to be set to display:relative, provide a width and align to center. For scroller and scroll bar will required more declaration.

#scrollcontainer
{
	margin: 0 auto;
	text-align: center;
	position: relative;
	width: 907px;
}
#scrollbar
{
	width: 907px;
	height: 40px;
	position: absolute;
	top: 0;
	left: 0;
	background: transparent url('../images/scrollbar.png')  no-repeat;
}
#scroller
{
	background: transparent url('../images/scroller.png') no-repeat;
	width: 196px;
	height: 40px;
	position: absolute;
	left: 0px;
	top: 0px;
}

Basically i set my scroll bar width and height so that the image can be placed into it. Finally, the container with the scroll bar image is set to position absolute with the top and left set to '0' in order for all browser to align properly ( or else you will see IE having problem). Similarly, the scroller part was also being done in this way. Simple enough.

jQuery

As usual, this is the most complex part which you should focus more. We will need to define some variable before we attached any event handler and other operation.

	var myoffset = $('#scroller').offset();
	var myxpos = parseInt(myoffset.left); 
	var width = parseInt($('#scrollbar').css("width")) - 196;
	var action = false;

We will need to declare the above variable so that we can easily maintain them when required without manipulate the inside logic of the slider. The variables are explain below,

  • myoffset: this is the offset position of the 'scroller' container. Similarly, this object return contains 'scroller' position
  • myxpos: using 'myoffset' object, we retrieve the 'x-axis' position
  • width: this is the actual width of the scroll bar (we substract 196 because the scroller width is 196px)
  • action: this is to indicate whether the scroller was clicked and holded

Now we will have to grab the coordinate of the mouse position and attach the event handler required for the slider to work.

	$().mousemove(function(e){
		
	})

The above will gives us the position of our mouse coordinate. Now will will look at the overall code within mousemove declaration.

	$().mousemove(function(e){
		var move = parseInt(e.pageX-myxpos);
		
		$('#scroller').mousedown(function(){
			action = true;
		})
		$('*').mouseup(function(){
			action = false;
		});
		
		if(move <= 0)
			move =0;
		if(move >= width)
			move = width;
		if(action)
		$('#scroller').css("left", (move)+"px");
				
	})

The 'move' variable gives us the real mouse position. Since the most left of the screen will gives us '0px' but it is not necessary that the scrollbar will always be at the most left of the screen. It can be at the center of the screen where the position of its starting point is also '0px'. Thus, we will need to subtract away the distance between the scroll bar containers and most left of the screen. Short to say, our mouse X coordinate will always be bigger than our scroll bar X coordinate. So we will have to make it similar by doing some subtraction.

The 'move' variable is troublesome explanation, let's move on. We attached two event handler to mousedown and mouseup to detect whether the user clicked on the 'scroller'.

Finally, we will detect whether the 'real mouse position' has moved over the constrained area and set the 'real mouse position' to the minimum or maximum of the area (indicate black on the concept section image). This is required so that it can move smoothly when it reaches the end of the scroll bar. We also use the variable 'action' to detect whether the 'scroller' was clicked before it is able to move.

The overall jQuery code for a slider to work is as follow,

$(function(){
	var myoffset = $('#scroller').offset();
	var myxpos = parseInt(myoffset.left); 
	var width = parseInt($('#scrollbar').css("width")) - 196;
	var action = false;
	
	$().mousemove(function(e){
		var move = parseInt(e.pageX-myxpos);
		
		$('#scroller').mousedown(function(){
			action = true;
		})
		$('body').mouseup(function(){
			action = false;
		});
		
		if(move <= 0)
			move =0;
		if(move >= width)
			move = width;
		if(action)
		$('#scroller').css("left", (move)+"px");	
	})
});

P.S: This is just a simple version on how slider can be done. It can definitely be improved! But this is just to illustrate a Silder for your understanding.

P.S: The full version without using jQuery Plugin or UI can be found at Tutorial: How to make your own simple and nice Slider with jQuery part 2

The Demo

The explanation might not work for you let's look at the demo i prepared which locate at jQuery slider demo, the image can be seen below,
jquery-slider-demo
Unfortunately, i did not make the container dynamic (means you can move them around) to test the important of the 'move' variable as describe above. Nonetheless, you can always download the demo down to your local PC at jQuery Slider demo files and modify the CSS position to test the slider! Hope you learn something too!

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!