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!

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:

Tutorial: jQuery wrap doesn’t work in IE

This is something happen to me a while ago when i am testing my WordPress plugin over different browser (testing cross browser issue). Every browser work well (Firefox, Opera, Chrome, Safari) but IE went wrong. Not surprising IE is the king for being different and causing most problem to developers (well known fellow). Oddly, IE is pointing its finger on one of the line related to jQuery wrap manipulation operation. Weird.

Problem

After debugging a while, i manage to find the problem that is happening with IE and not with other browsers. I used wrap operation to insert a form into a div container (to perform a asynchronous upload over different browser and try not to knock on WordPress style sheet etc.). So the form should wrap over the div container as stated in jQuery documentation. However, in IE it couldn't seems to find this particular new form that was inserted through the wrap operation (scratch head). Since this is a JavaScript DHTML operation, obviously it won't show during view source (at least not for IE). Through the error line instructed by IE browser it indicated that the particular form ID could not be found (form doesn't exist). jQuery warp doesn't support IE 7? Nah..

Solution

So what is going on? Many jQuery users will like to write a wrap operation in this way (including me)


$('#example').wrap('<form id="form2" name="form" action="#" method="POST" enctype="multipart/form-data" >');

This is perfectly alright to wrap a form over some div block. Nothing seems to be wrong as it can be declare this way. Well, most of us will do that since it doesn't add additional word to lengthen the instruction which always make it a bit difficult to read (due to jQuery chaining). However, if you declare it this way using the wrap operation, IE will not work! The wrap operation basically fail without showing any error indicating that the new form which was instructed to create was not there. Good news is that it is not really jQuery fault that it doesn't work when declaring a wrap operation this way. In order for jQuery v1.3 to work in IE using the wrap operation, the declaration must be in this form


$('#example').wrap('<form id="form2" name="form" action="#" method="POST" enctype="multipart/form-data" ></form>');

seems no differences between the two code. But the key is the closing tag which is that ONLY requirement for IE to work flawlessly. Without the closing tag it will not work.

Demo

let me show you a demo to illustrate the differences between the two declaration using the following JavaScript.


$(function(){
	$('#wrong').wrap('<form id="form1" name="form" action="#" method="POST" enctype="multipart/form-data" >');
	$('#correct').wrap('<form id="form2" name="form" action="#" method="POST" enctype="multipart/form-data" ></form>');
});

function withoutCloseTag()
{
	if(document.getElementById('form1') != null && document.getElementById('form1') != "undefined")
	{
		alert("We found wrap for button 'IE with problem'");
	}
}

function withCloseTag()
{
	if(document.getElementById('form2') != null && document.getElementById('form2') != "undefined")
	{
		alert("We found wrap for button 'IE without problem'");
	}
}

The script will alert if the usage of wrap is successful and when fail it will not show any alert message. Try this in IE with other browser. You will find that the second declaration work flawlessly over all browser while the first declaration will only work on all browser except IE (IE no pop out).

Conclusion

Unlike some jQuery tutorial online that teaches the basic of jQuery that indicates the first method of declaration work (without closing tag). It is necessary for jQuery developers to know the differencces between declaring a DHTML operation using jQuery that a closing tag will make a differences when your application is serving different browser.

$(function(){
$('#wrong').wrap('
');
$('#correct').wrap('
');
});
function withoutCloseTag()
{
if(document.getElementById('form1') != null && document.getElementById('form1') != "undefined")
{
alert("We found wrap for button 'IE with problem'");
}
}
function withCloseTag()
{
if(document.getElementById('form2') != null && document.getElementById('form2') != "undefined")
{
alert("We found wrap for button 'IE without problem'");
}
}

jQuery Menu Effect Plugin

There are 6 effects contain in this small plugin that i created casually for the purpose for making the overall menu bar more interesting. The plugin itself is quite easy to use but it may contain many unnecessary code since you will only be using a single effect of the plugin, others will be just there to sum up the size of the file. Therefore, if you would like to only use one of the effect in this small plugin, just remove the other effect located in the plugin. Feel free to see how each effect work, you can also search this site for the how-to tutorial on each of the effect in jQuery.

Information

  • Current version: 1.0
  • Licensing: MIT

Browser Tested

  • Firefox 3.0.7
  • IE 7.0.5730.13
  • Opera 9.64
  • Google Chrome
  • Safari

Dependencies

  • jQuery 1.31

Documentation

I will keep the documentation simple, each method will have certain parameter that can be adjust such as speed of the effect and etc. by default, all these effect already have their own default values. Therefore, without any changes you can also call it out by stating its method.

There are 6 effects altogether.

  1. OthersFade()
  2. OthersJump()
  3. OthersBlink()
  4. OthersRollUp()
  5. OthersRollDown()
  6. OthersVibrate()

Each effect can be viewed on the demo page.  In order to call each effect, you will just have to do the following,


$("div#menu1 ul#main li").OthersFade();
$("div#menu2 ul#main li").OthersJump();
$("div#menu3 ul#main li").OthersBlink();
$("div#menu4 ul#main li").OthersRollUp();
$("div#menu5 ul#main li").OthersRollDown();
$("div#menu6 ul#main li").OthersVibrate();

bear in mind that the selection on jquery must be pointing at the element '

  • ' and the parameter of each effect is stated below,

    OthersFade()

    • startOpacity: 1, //the start visibility
    • hoverOpacity: 0, //the hover visbility
    • duration: 2000  //the effect duration to reach hover opacity

    OthersJump()

    • jumpHeight: 15, //how height it jump
    • jumpDirection: 0, //'0' jump upwards, '1' jump downwards
    • duration: 100  //duration of the effect

    OthersBlink()

    • brightness: 0.5 //the quickness of the effect
    • duration: 100 //duration of effect

    OthersRollUp()

    • duration: 1000 //speed of effect

    OthersRollDown()

    • duration: 1000 //speed of effect

    OthersVibrate()

    • interval: 30,  // the start interval of each vibration
    • duration: 1000, // the duration of the vibration
    • shake: 3 //the area that the vibration will be moving

    Support

    • Please post bug reports and other contributions (enhancements, features, etc.) to [email protected] and i will try to get back to you asap. You can comment below to seek help too.
    • Any additional effect you would like to have in this plugin, please comment below or email me so that i can add them up.
    • There are a lot of how-to effect in this particular site, feel free to search for it and learn up yourself to get this effect on your own plugin

    Donation

    [donate]

    Update

    • initial released

    File

    Example of usage

    interval: 30,
    duration: 1000,
    shake: 3