I have successfully built a login form using ajax and want to add a shake effect to the form when the user enters incorrect details. I have the function in place that will f
Why bother?
Animations are queued.
More - instead a left attribute you can use margin-left what prevents to adding position attribute :)
function shakeForm() {
var l = 20;
for( var i = 0; i <= 10; i++ ) {
$( 'form' ).animate( {
'margin-left': '+=' + ( l = -l ) + 'px',
'margin-right': '-=' + l + 'px'
}, 50);
}
}
loop throw the array using jQuery.each: http://jsfiddle.net/N8F7Z/1/
function shakeForm() {
var p = "15 30 15 0 -15 -30 -15 0".split(" ");
$.each(p, function(key, value) {
var delay = 100;
setTimeout(function() {
$("form").css("left", value + "px");
}, delay*key);
});
}
A simple way to make an array is splitting a string with every space:
var p = "15 30 15 0 -15 -30 -15 0".split(" ");
The delay between each step:
var delay = 100;
Using setTimeout(function() {...}, theTimeBeforeFiring )
theTimeBeforeFiring = delay * key
key is the key the value has in the array:
key = 0, 1, 2, 3
mmm why use native js if jquery animate() is available... you try recurring like this:
var p = new Array(15, 30, 15, 0, -15, -30, -15, 0);
function shakeForm(index) {
if(typeof index === "undefined") index = 0;
if(typeof p[index] === "undefined") return false;
$("form").animate({
"left": p[index]
}, function() {
shakeForm(index + 1);
});
}
For those of you who are stubborn (like me) and hate libraries...
var e = document.getElementById('dividname');
e.style.marginLeft='8px';
setTimeout(function(){e.style.marginLeft='0px';},100);
setTimeout(function(){e.style.marginLeft='8px';},200);
setTimeout(function(){e.style.marginLeft='0px';},300);
then in your css:
.shakeClass{
transition: margin 100ms;
}
I have made a plugin for this .. check it http://static.mbiosinformatica.com.br/jQuery/
Is it working in IE ( 7 , 8 , 9 ) , Chrome and Firefox.
And, you can apply a callback function, to show error message .. or anything else.
$('#div').shake({
positions : { 'L' : 50 , 'R' : 50 } , // shake only left and right (U,L,R,D)
rotate : false , // rotate div on shake .. true/false
parent : false // shake parent div .. true/false
}, function(){ /* do something */ });
In the positions, you can send array too, just: positions: [ [ 'L', 50 ... ] ]
This value '50' its the shake distance from original position ..
To change timeout ( delay ) and effect duration, you have to set timeout: [you timeout .. / delay ] and the effect times .. interval: ...
Its better to use CSS to this instead of JS. CSS uses less resources(is faster) and its simpler. You can find good (and 'ready to use') examples here: https://daneden.me/animate/