Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Bounce Effect on click no jQuery UI

I cannot find a solution to an animation to make a div bounce, using just jQuery animations. Something like does not work:

$("#bounce").click(function() {
    $(this).effect("bounce", {
        times: 3
    }, 300);
});.​

I would prefer not to use jQuery UI or any external plugin, such as the easing one. A wobble effect would be just as good in my case, so either will do.

Here is an example, any help would be much appreciated! Thanks in advance

like image 893
jacktheripper Avatar asked Apr 28 '12 12:04

jacktheripper


2 Answers

You could simply chain together some animate calls on the element like so:

$("#bounce").click(function() {
    doBounce($(this), 3, '10px', 300);   
});


function doBounce(element, times, distance, speed) {
    for(var i = 0; i < times; i++) {
        element.animate({marginTop: '-='+distance}, speed)
            .animate({marginTop: '+='+distance}, speed);
    }        
}

Working example: http://jsfiddle.net/Willyham/AY5aL/

like image 103
Will Demaine Avatar answered Sep 19 '22 07:09

Will Demaine


Use this function for damped bounces. Be sure to give the bouncing element a unique class if using the code without changes.

var getAttention = function(elementClass,initialDistance, times, damping) {
  for(var i=1; i<=times; i++){
      var an = Math.pow(-1,i)*initialDistance/(i*damping);
      $('.'+elementClass).animate({'top':an},100);
  }
  $('.'+elementClass).animate({'top':0},100);
}

$( "#bounce").click(function() {
	getAttention("bounce", 50, 10, 1.2);
});
#bounce {
    height:50px;
    width:50px;
    background:#f00;
    margin-top:50px;
    position:relative;
    border-radius: 50px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bounce" class="bounce"></div>
like image 25
christian Avatar answered Sep 19 '22 07:09

christian