Em Ji Madhu Em Ji Madhu - 2 months ago 12
CSS Question

Changing value greater than or less than the given value, doesn't work in jQuery?

First of all this isn't a new question — I'm just referencing another question which was asked already on Stack Overflow:

Bouncing ball 5 times jquery/javascript beginners level

In that question, the animation was working fine for bounces 5 times, but when I try with more than 5 or less than 5, doesn't seem to properly work.

In case of emergency here is the snippet:



$(function() {

var time = 500;
var bounces = 8;
var top_bounce = 20;

function bounceDown() {
$("#ball").animate({
left: 10,
top: 100
}, time, function() {
bounceUp();
});
};

function bounceUp() {
$("#ball").animate({
top: top_bounce
}, time);
top_bounce = top_bounce + 20;
};

function shadowUp() {
$("#shadow").animate({
width: 100,
height: 5,
left: 10,
top: 200,
opacity: 1
}, time,
function() {
shadowDown();
});
};

function shadowDown() {
$("#shadow").animate({
width: 0,
height: 0,
left: 15,
top: 200,
opacity: 0
}, time);
};

function finalDown() {
$("#ball").animate({
left: 10,
top: 100
}, time);
};

function finalShadow() {
$("#shadow").animate({
width: 100,
height: 5,
left: 10,
top: 200,
opacity: 1
}, time);
};

$('#Get').click(function() {
for (var i = 0; i < bounces; i++) {
setTimeout(function() {
bounceDown();
shadowUp();
}, time * 2 * i);
setTimeout(function() {
finalDown();
finalShadow();
}, 5000);
};
});
});

body {
background-color: black;
position: absolute;
width: 100%;
height: 100%;
overflow: hidden;
}
#container {
position: absolute;
left: 50%;
width: 500px;
height: 700px;
}
#ball {
width: 100px;
height: 100px;
position: absolute;
background-color: #e65454;
border-radius: 50%;
}
#shadow {
position: absolute;
height: 5px;
width: 100px;
background: radial-gradient(ellipse at center, rgba(91, 91, 91, 1) 0%, rgba(142, 142, 142, 0.84) 16%, rgba(227, 228, 229, 0) 100%);
/* W3C */
filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#5b5b5b', endColorstr='#00e3e4e5', GradientType=1);
opacity: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<button id="Get">Set</button>

<div id="container">
<div id="ball"></div>
<div id="shadow"></div>
</div>




Answer

You have to:

  1. Increase bounces
  2. Decrease top_bounce so the ball won't stick to the bottom too fast
  3. Increase the time in setTimeout so the ball will have time to complete the bounces

DEMO