How to call a function with a delay - javascript

I have the following function, which animates a series of bars:
function fluctuate(bar) {
var height = Math.floor(Math.random() * 30) + 5;
//Animate the equalizer bar repeatedly
bar.animate({
height: height
}, 250, function() {
fluctuate($(this));
});
}
$(".bar").each(function(i) {
fluctuate($(this));
});
I want this to play each time a div class (".play") is clicked. How can I enabled this, and limit the animation to 3 seconds, before stopping?
Thanks

To run the animation for three seconds only, count the number of times it has been running, and multiple with the animation speed to get the total sum of the animations length :
function fluctuate(bar) {
var height = Math.floor(Math.random() * 30) + 5;
bar.animate({
height: height
}, 250, function() {
var times = $(this).data('times') || 0;
if (times <= 12) {
$(this).data('times', ++times);
fluctuate($(this));
}else{
$(this).data('times', 0);
}
});
}
$(".bar").each(function(i) {
fluctuate($(this));
});
FIDDLE
And a nicer version as a plugin with parameters:
$.fn.fluctuate = function(speed, duration) {
return this.each(function() {
var self = this,
times = Math.round(duration / speed),
iteration = 0;
(function ani() {
var height = Math.floor(Math.random() * 30) + 5;
$(self).animate({ height: height }, speed, function() {
if (iteration <= times) {
iteration++;
ani();
}
});
})();
});
}
$('#test').on('click', function() {
$(".bar").fluctuate(250, 3000);
});
FIDDLE

Related

Get elements coordinates

I need some help here.
First off, here is a small demo code from my game: https://jsfiddle.net/MiloSx7/a0dn9a4f/2/
Animation idea: Make the coin scale to 2x after it's collected, then slowly move it and gradually reduce scale to the exact spot where the image displaying the coin inventory stat is , invLocation is the ID of the element where the animation should end. It starts from the current coinId X and Y
Is it possible to somehow get the X and Y of the invLocation, so that I know where should I tell the animation to move?
You can do this with JQuery position() and offset() methods.
const spawnTime = 10000;
var coin = 0;
var intervalId = '';
var coinDiv = $('#coinDiv');
var coinImg = $('#coinImg');
var invDiv = $('#invDiv');
var invId = $('#inventoryId');
var invImg = $('#invLocation');
coinImg.on('click', collect);
intervalId = setInterval(setLocation, spawnTime);
function setLocation() {
var x = parseInt( Math.random()*(80-20+1) ) + 20;
var y = parseInt( Math.random()*(80-20+1) ) + 20;
coinImg.animate({
opacity: 1
}, 3000,
function() {
coinImg.css('top', x+'%');
coinImg.css('left', y+'%');
coinImg.css('display', 'initial');
setTimeout( () => coinImg.animate({ opacity: 0 }, 3000), 6000);
});
}
function collect() {
clearInterval(intervalId);
coinImg.stop();
coinImg.css('opacity', 1);
/* Increment coin counter */
coin++;
invId.text(coin);
/* In order to disable multiple clicks */
coinImg.css('pointer-events', 'none');
/* Double the size */
coinImg.css('width', '128px');
coinImg.css('height', '128px');
/* Animate and return to normal */
coinImg.animate({
width: '32px',
height: '32px',
left: invImg.offset().left + 'px',
top: invImg.offset().top + 'px'
}, 1500,
function() {
coinImg.css('pointer-events', 'auto');
coinImg.css('display', 'none');
coinImg.css('width', '64px');
coinImg.css('height', '64px');
intervalId = setInterval(setLocation, spawnTime);
}
);
}
Working example: https://jsfiddle.net/wz4q9w69/

jQuery - end setinterval after X rund

I have a little slider im working on which is almost there im jsut having some trouble with me jQuery.
So first off:
I want my slider to reset after the interval has run x amount of times.
It was my understanding that the following would work but it doesn't seem to take. 6000, slides, function() { homesliderend();
so lets say slides = 2 set interval should call homesliderend(); but it doesn't the interval just keeps running.
Second Issue: I'm also trying to get it to add 100% to lengther every 6 seconds. But instead of adding 100 each time its just setting it to 100 its not multiplying.
jQuery(document).ready(function($) {
"use strict";
function homesliderend() {
$(".lengther").animate({
left: "0%"
}, 500);
}
function homeslider() {
var slides = $(".slide.t-align").length,
lwidth = slides * 100,
n = 0;
$(".lengther").css("width", lwidth + "%");
setInterval(function() {
var tn = n + 100;
$(".lengther").animate({
left: "-" + tn + "%"
}, 500);
}, 6000, slides, function() {
homesliderend();
});
}
homeslider();
});
The setInterval will not stop automatically, you need to clear the interval to stop it.
Also you need to increase the value of n to increase the left param
jQuery(document).ready(function ($) {
"use strict";
function homesliderend() {
$(".lengther").animate({
left: "0%"
}, 500);
}
function homeslider() {
var slides = $(".slide.t-align").length,
lwidth = slides * 100,
n = 0;
$(".lengther").css("width", lwidth + "%");
var interval = setInterval(function () {
var tn = ++n * 100;
$(".lengther").animate({
left: "-" + n + "%"
}, 500);
//if the last item is slided then stop the animation and run homesliderend
if (n == slides) {
clearInterval(interval);
homesliderend();
}
}, 6000);
}
homeslider();
});

Make animation with several div's in a loop

I have a working animation jquery script here: jsfiddle
var speed = 1500;
var margin = 50;
var start = 200;
var next = 1400;
setTimeout(function() {
$("#foo").show().animate({
// marginLeft: startPoint,
marginLeft: margin // endPoint
}, speed);
},start + next * 0);
setTimeout(function() {
$("#bar").show().animate({
// marginLeft: startPoint,
marginLeft: margin // endPoint
}, speed);
},start + next * 1);
setTimeout(function() {
$("#foobar").show().animate({
// marginLeft: startPoint,
marginLeft: margin // endPoint
}, speed);
},start + next * 2);
I would like to change all the div id's into classes and then run a loop in jquery instead - similar to this: animating-several-divs-in-a-sequence.
$(function () {
function show() {
$('.project_box:not(.completed):first').show(500, function () {
$(this).addClass('completed');
show();
});
}
show();
});
I would also like to run the animation from outside the body-tag ("startPoint") and make it end at its current "endPoint".
Any help is much appreciated!
Note: Please have in mind, that I'm a newbie into jQuery and English is not my spoken language. :-)
Here suppose you name the class as class="test". you can do this :
$(document).ready(function(){
var speed = 1500;
var margin = 50;
var start = 200;
var next = 1400;
$('.test').each(function(index,element){
setTimeout(function() {
$(element).show().animate({
// marginLeft: startPoint,
marginLeft: margin // endPoint
}, speed);
},start + next * index);
});
});
see here : http://jsfiddle.net/w7o0vezs/

fadeIn and fadeOut functions not working

I am working on fadein and fadeout functions using pure javascript, here is the code:
(function() {
var fx = {
easing: {
linear: function(progress) {
return progress;
},
quadratic: function(progress) {
return Math.pow(progress, 2);
},
swing: function(progress) {
return 0.5 - Math.cos(progress * Math.PI) / 2;
},
circ: function(progress) {
return 1 - Math.sin(Math.acos(progress));
},
back: function(progress, x) {
return Math.pow(progress, 2) * ((x + 1) * progress - x);
},
bounce: function(progress) {
for (var a = 0, b = 1, result; 1; a += b, b /= 2) {
if (progress >= (7 - 4 * a) / 11) {
return -Math.pow((11 - 6 * a - 11 * progress) / 4, 2) + Math.pow(b, 2);
}
}
},
elastic: function(progress, x) {
return Math.pow(2, 10 * (progress - 1)) * Math.cos(20 * Math.PI * x / 3 * progress);
}
},
animate: function(options) {
var start = new Date;
var id = setInterval(function() {
var timePassed = new Date - start;
var progress = timePassed / options.duration;
if (progress > 1) {
progress = 1;
}
options.progress = progress;
var delta = options.delta(progress);
options.step(delta);
if (progress == 1) {
clearInterval(id);
options.complete();
}
}, options.delay || 10);
},
fadeOut: function(element, options) {
var to = 1;
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return fx.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to - delta;
}
});
},
fadeIn: function(element, options) {
var to = 0;
this.animate({
duration: options.duration,
delta: function(progress) {
progress = this.progress;
return fx.easing.swing(progress);
},
complete: options.complete,
step: function(delta) {
element.style.opacity = to + delta;
}
});
}
};
window.fx = fx;
})()
I am using the following code to activate the function:
document.getElementById('in').addEventListener('click', function() {
FX.fadeIn(document.getElementById('type'), {
duration: 2000,
});
}, false);
But when I load the page I get an error with the activation code.
Does anyone know what I have done wrong?
Thank you so much.
With a few adjustments, your code should work fine...
As Richard Dalton noticed, call the object with fx not FX.
Add default values for all options in case an option isn't provided (your example code throws an error because options.complete is undefined). Example:
this.animate({
duration: options.duration || 1000,
...
complete: options.complete || function() { },
...
});
Adjust the styles before animating (imagine an element is hidden using display: none instead of opacity: 0)... Example (for fadeIn):
element.style.opacity = 0;
element.style.visibility = "visible";
element.style.display = "block";
Check if an action is needed at all (e.g. call to fadeIn despite element already being visible):
isVisible: function(element) {
return element.style.display !== "none" &&
element.style.visibility !== "hidden" &&
element.style.opacity !== "0";
}
// In fadeIn:
if (!this.isVisible(element)) {
...
}
Here's the corrected code with an example: JSFiddle
Certainly one could tweak this a little further, deal with some corner cases (e.g. what happens if there is a call to fadeIn while the element is currently being faded out?), and I'm pretty sure it doesn't work in all browsers (old IEs)... But I hope I pointed you in the right direction. :)

Create Random Falling Object in Jquery

I trying to make the div fall from top to bottom.
Here is the code that i tried but it doesn't satisfy my needs .I want to generate the 20 div once ready then how to make that 20 div falling continuously from top to bottom consistently. Is it possible to do that in jquery.
http://jsfiddle.net/MzVFA/
Here is the code
function fallingSnow() {
var snowflake = $('<div class="snowflakes"></div>');
$('#snowZone').prepend(snowflake);
snowX = Math.floor(Math.random() * $('#site').width());
snowSpd = Math.floor(Math.random() + 5000);
snowflake.css({'left':snowX+'px'});
snowflake.animate({
top: "500px",
opacity : "0",
}, snowSpd, function(){
$(this).remove();
fallingSnow();
});
}
var timer = Math.floor(Math.random() +1000);
window.setInterval(function(){
fallingSnow();
}, timer);
Much Appreciate your Help.
Thanks
Not sure if this is what you want.
I am animating 20 snowflakes, wait until animation finishes for all of them, then restart all over again.
jsfiddle
function fallingSnow() {
var $snowflakes = $(), qt = 20;
for (var i = 0; i < qt; ++i) {
var $snowflake = $('<div class="snowflakes"></div>');
$snowflake.css({
'left': (Math.random() * $('#site').width()) + 'px',
'top': (- Math.random() * $('#site').height()) + 'px'
});
// add this snowflake to the set of snowflakes
$snowflakes = $snowflakes.add($snowflake);
}
$('#snowZone').prepend($snowflakes);
$snowflakes.animate({
top: "500px",
opacity : "0",
}, Math.random() + 5000, function(){
$(this).remove();
// run again when all 20 snowflakes hit the floor
if (--qt < 1) {
fallingSnow();
}
});
}
fallingSnow();
Update
This version creates 20 divs only once, and animate them again and again.
jsFiddle
function fallingSnow() {
var $snowflakes = $(),
createSnowflakes = function () {
var qt = 20;
for (var i = 0; i < qt; ++i) {
var $snowflake = $('<div class="snowflakes"></div>');
$snowflake.css({
'left': (Math.random() * $('#site').width()) + 'px',
'top': (- Math.random() * $('#site').height()) + 'px'
});
// add this snowflake to the set of snowflakes
$snowflakes = $snowflakes.add($snowflake);
}
$('#snowZone').prepend($snowflakes);
},
runSnowStorm = function() {
$snowflakes.each(function() {
var singleAnimation = function($flake) {
$flake.animate({
top: "500px",
opacity : "0",
}, Math.random() + 5000, function(){
// this particular snow flake has finished, restart again
$flake.css({
'top': (- Math.random() * $('#site').height()) + 'px',
'opacity': 1
});
singleAnimation($flake);
});
};
singleAnimation($(this));
});
};
createSnowflakes();
runSnowStorm();
}
fallingSnow();
Update2
This one that initializes the left once the animation is done for each snowflake, looks more natural in my opinion.
Also changed the delay from
Math.random() + 5000
to
Math.random()*-2500 + 5000
demo
This is simple.
Your design of function must be this.
function snowflake()
{
if($(".snowflakes").length <= 20)
{
generate_random_snowflake();
}
else
{
call_random_snowflake();
}
}
check this out, pretty simple i just added a function that triggers jquerysnow() and then calls itself again wit random time
updated code now it will just create 20 snow flakes
snowCount = 0;
function snowFlakes(){
console.log(snowCount);
if(snowCount > 20){
return false
}else{
var randomTime = Math.floor(Math.random() * (500) * 2);
setTimeout(function(){
snowCount = snowCount +1;
jquerysnow();
snowFlakes();
},randomTime);
}
}
function jquerysnow() {
var snow = $('<div class="snow"></div>');
$('#snowflakes').prepend(snow);
snowX = Math.floor(Math.random() * $('#snowflakes').width());
snowSpd = Math.floor(Math.random() * (500) * 20);
snow.css({'left':snowX+'px'});
snow.html('*');
snow.animate({
top: "500px",
opacity : "0",
}, 2000, function(){
$(this).remove();
//jquerysnow();
});
}
snowFlakes()
http://jsfiddle.net/v7LWx/22/

Categories