Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to shake a div vertically using JQuery shake

Tags:

jquery

I use this code to shake a div

$(".target").effect( "shake", 
      {times:4}, 1000 );

Is it possible to shake vertically and also set height of shake

like image 227
Andy Avatar asked Nov 29 '22 08:11

Andy


2 Answers

Here is how I would do it using simple jQuery and JavaScript knowledge: setInterval:

jQuery.fn.shake = function() {
    $el = $(this);
    setInterval(function(){ 
        if ($el.hasClass('shake')) {
            $el.removeClass('shake');
        } else {
            $el.addClass('shake');
        };  
    }, 320);
};

$('.button').shake();

Adding and removing a class uses less resources than modifying properties in DOM. And we can also take advantage of CSS transitions applied to our .button:

.button {  margin-top: 0;
    -webkit-transition: margin-top 300ms ease-out;
    -moz-transition: margin-top 300ms ease-out;
    -o-transition: margin-top 300ms ease-out;
    transition: margin-top 300ms ease-out; }
.button.shake { margin-top: 15px; }

Final note, make sure your .button element is placed in a div with position: absolute so it doesn't push around everything below it.

like image 42
Vali Munteanu Avatar answered Dec 10 '22 21:12

Vali Munteanu


You can set the options called direction and distance as shown in the Shake Effect API.

$(".target").effect( "shake", { direction: "up", times: 4, distance: 10}, 1000 );

jsFiddle Demo


Shake Effect API

direction (default: "left")

Type: String A value of "left" or "right" will shake the element horizontally, and a value of "up" or "down" will shake the element vertically. The value specifies which direction the element should move along the axis for the first step of the effect.

distance (default: 20)

Type: Number Distance to shake.

like image 54
Itay Avatar answered Dec 10 '22 23:12

Itay