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'");
}
}

Tutorial: jQuery Fold Effect Concept And Explanation

In this tutorial, i will explain the concept and ways of making a fold effect in jQuery. Such effect can be apply to different context such as image gallery or even just add on effect for your design work.

Concept

Depending on whether you wish to fold away your content or you wish to fold out your content. Folding in your content will be to pull up the content and slide it outward while folding out your content will be to push your content out and slide it downwards. There are two way of achieving this effect. One is to use the viewport technique which will lengthy your code and complex your stuff but generally give you a better visualize effect than the next effect. The next effect that can achieve this with only few lines of code is typically using CSS and animate function in jQuery.

Coding

On the HTML part, you will most likely will only required the following set of div block

<div class='image' id='box1'></div>
<div class='image' id='box2'></div>
<div class='image' id='box3'></div>
<div class='image' id='box4'></div>

On the CSS coding, you will most likely need the following


body{
margin: 0 auto;                    /*align the header at the center*/
text-align: center;                /*align the header at the center*/
}

div.image
{
width: 600px;                    /* width of each container*/
height: 350px;                    /* height of each container*/
position: absolute;                /* instructure each container to obey the position absolutely*/
float: left;                    /* float all the container so that they overlapped each other*/
left: 27%;                        /* align them to the center of the screen */
z-index: -1;
}

div#box1
{
background: #66A666 url('../images/blue.png');
}
div#box2
{
background: #E37373 url('../images/green.png');
}
div#box3
{
background: #B2B2B2 url('../images/orange.png');
}
div#box4
{
background: #A51515 url('../images/red.png');
}

The above codes are similar to the opening door effect tutorial i did previously.

On the jQuery coding,

$(function(){
var i = -1;
$('div.image').click(function(){
$(this)
.animate({height: 50+'px'}, 500)
.animate({width: 0+'px'}, 500, function(){$(this).css('z-index', i);
$(this).css({height: 350+'px', width: 600+'px'});});
i--;
});
})

this is all you required. What i did is basically add an event handler to each div block and perform an animate function to adjust the height of the effect to a certain visible amount and slide the height to 0 once the height animate has completed which will gives us a nice fold effect. Once the fold effect has been completed, i push the image back to the queue by setting its z-index and return its original size. This way is much better than using a view port which will block the next image and create a not very impressive fold effect.

You can visit the demo site for this fold effect tutorial. The tutorial files can be retrieve from jquery-fold-effect-tutorial

Tutorial: How to make your own opening and closing door effect with jQuery

The kind words from some of you guys really makes me wanted to write more advance tutorial but i really have limited time. Nonetheless, i will try my best to write at least 1 tutorial in the most easiest and detail form as much as i can. In this tutorial, i will show you a more advance trick to perform a opening/closing door effect. This tutorial will deal with viewport to perform such effect and may get a little confusing. The demo is as usual at the bottom of the tutorial. If you would like to view the demo first before reading, please proceed to the bottom of this tutorial instead.

Concept

Imagine you have a sliding door, one left and one right. In order to open/close this particular door, we have to pull or push both door so that it will open or close completely. This is the usual case for a door to open and close which required two image of door left and right. How can this be done? The concept behind this technique is not similar to the zoom tutorial i did previously. But let's just concentrate on what is a viewport. A viewport is just a viewable area on the screen to the user, anything outside the viewport is considered unseen by the user. Using viewport, we will try to hide the two sliding door left and right outside the viewport and when the user clicks on the image, the door will automatically be called in and closed the door to create a nicely done closed door effect. The opening door effect will be exactly the same with the additional step to open the door after the door is closed.

CSS and HTML

I believe the CSS and HTML structure should be the same as the shuffle effect tutorial i wrote previously.

Coding

The coding part may get a bit confusing for the viewport technique. But i will try my best to cover it with simplicity as much as i can. If there is any doubt you may have you can really comment below and i will try to reply you within the day if possible. On the CSS Coding,


body{
margin: 0 auto;                    /*align the header at the center*/
text-align: center;                /*align the header at the center*/
}

div.image
{
width: 600px;                    /* width of each container*/
height: 350px;                    /* height of each container*/
position: absolute;                /* instructure each container to obey the position absolutely*/
float: left;                    /* float all the container so that they overlapped each other*/
left: 27%;                        /* align them to the center of the screen */
z-index: -1;
}

div#box1
{
background: #66A666 url('../images/blue.png');
}
div#box2
{
background: #E37373 url('../images/green.png');
}
div#box3
{
background: #B2B2B2 url('../images/orange.png');
}
div#box4
{
background: #A51515 url('../images/red.png');
}

Notice that everything above are images and if images are not displayed yet, a color will be shown instead. Other important stuff are self explained on the comment i wrote in the code. For the HTML structure,

<div class='image' id='box1'></div>
<div class='image' id='box2'></div>
<div class='image' id='box3'></div>
<div class='image' id='box4'></div>

There will only be the container in the HTML structure similar to the shuffle effect tutorial. Supposely, it should have more than just 4 block of div as we need a viewport for each container. But for simplicity, i will just write 4 block here and leave all the complex stuff with jQuery. On the jQuery side,

//below here preload the image in the simplest form
$(function(){
for(i = 1; i < 5;i++)
{
var img = new Image();
img.src = 'images/images/d_left_'+i+'.png';
$(img).load();
}

var i = -1; //deep of the image
var no = 0; //image number

//attach event handler on each container/image
$('div.image').click(function(){
var Obj = $(this);
no++;
if(no > 4)
no = 1;

// viewport structure
Obj.wrap('
<div id='viewport'></div>
');
Obj.css({left: 0+'px'});
$('#viewport').css('overflow','hidden');
$('#viewport').width(Obj.width());
$('#viewport').height(Obj.height());
$('#viewport').css('left','27%');
$('#viewport').css('position','absolute');

// left door structure
$('#viewport').append('
<div class='GrpEffectDiv' id='doorLeft'/>');
$('#doorLeft').css('position', 'absolute');
$('#doorLeft').css('background', '#000 url('images/images/d_left_'+no+'.png')');
$('#doorLeft').width(Obj.width()/2);
$('#doorLeft').height(Obj.height());
$('#doorLeft').css('left', '-'+300+'px');

//right door structure
$('#viewport').append('
<div class='GrpEffectDiv' id='doorRight'/>');
$('#doorRight').css('position', 'absolute');
$('#doorRight').css('background', '#000 url('images/images/d_right_'+no+'.png')');
$('#doorRight').width(Obj.width()/2);
$('#doorRight').height(Obj.height());
$('#doorRight').css('left', 600+'px');

// left door animation
$('#doorLeft')
.animate({left: 0+'px'},1000,
function(){
Obj.css('z-index', i);
$(this).remove();
});

//right door animation
$('#doorRight')
.animate({left: 300+'px'},1000,
function(){
$(this).remove();
Obj.css({left: '27%'});
$('#viewport').replaceWith(Obj);
});

i--;
});
})

Seriously, looking at the code i am starting to wonder whether i will be able to explain it in a simple term.  Anyway, what the above code done is as follow,

  1. create a viewport around the container and became the parent of the container
  2. create the left door and append into the viewport ( doors became neightbour of the container)
  3. create the right door and append into the viewport
  4. animate both left and right door to close the door
  5. remove both door and subsituate the viewport back to the container with the original settings

I have also commented the code above so that you are clear what i am doing on the code itself. So how does the viewport be created by the code above? If you have read my sliding tutorial previously,  it is similar to the frame concept, where there is a frame (viewport) to cover the outside of the viewport. If i remove the most important thing for the viewport to work which is

$('#viewport').css('overflow','hidden');

You will see that the left and right box is standing by on the right and left side ready to charge at the container to close the door.

without overflow hidden
without overflow hidden

Notice the right and left image which i made? These are the door of the next image, this way we can create a very nice effect as shown in the demo

.

Improvement

There maybe people who will disagree with this tutorial that all the styling is placed on the jQuery script itself when we can actually just add a class on an external script and give the class to the div block object itself instead. You can definitely do that to simplify the efficiency and flexibility of the code. The purpose why it is done this way is to avoid any complexity on the CSS section. Personally, it will just confuse me going to look up and down on the post to feature out what i am doing. So i place it in a chunk of code indent it nicely for me and everyone to understand.=) The other thing you can do to improve the above code is to apply chaining which i always did in a whole straight line. Imagine if i do it in my tutorial? won't be that nice to read isn't it? Another thing is the preloader in this tutorial, it is just pure load image and may not do as well as other great pre loader but it basically how preloader work in jQuery. Thus, you may see black door on the first time during your loading instead of the image of the door until it cache the image to your browser that it! =X You can do this for gate closing and opening effect as well, we just have to do it on the top and bottom instead of left and right. Anyway, hope you like this tutorial as well =)

File

You can find the tutorial files by saving the page on the demo site. But if you feel lazy, you can download from jquery-closing-opening-door-effect