jQuery - end setinterval after X rund - javascript

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();
});

Related

setInterval setTimeout delay and pause for creating slide elements

I have 4 elements spread horizontally and I want to move them left every 3 sec, the thing that the 1st element and the 4th element are the same, so when we are at the 4th element I am changing back to the 1st without animation so the slides loop itself.
What happened is that the 1st/4th slide pauses twice the time.
I am looking for a way to solve it, I tried to change the "pause" var during the interval through the "if" but that seems impossible.
I tried to setTimeout inside the interval but they both work parallel
function setIntervalX(callback, delay, repetitions) {
var x = 0;
var intervalID = window.setInterval(function () {
callback();
if (++x === repetitions) {
window.clearInterval(intervalID);
}
}, delay);}
than this
var $post = $('.testi');
var x = -100;
var pause = 1500;
setIntervalX(function () {
$post.css('transform', 'translateX(' + x + '%)');
if ( x == -400 ){
$('.testi').css('transition', '0s');
$('.testi').css('transform', 'translateX(0)');
x = -100;
}
else {
setTimeout(function(){
$('.testi').css('transition', '1.5s ease');
x = x - 100;
}, 1500);
}
}, pause, 100);
When x reaches -400, you need to bring it back to -100 immediately, without an timeout cycle.
Try this:
var $post = $('.testi');
var x = -100;
var pause = 1500;
setIntervalX(function () {
if ( x == -400 ){
$('.testi').css('transition', '0s');
$('.testi').css('transform', 'translateX(0)');
x = -100;
}
$post.css('transform', 'translateX(' + x + '%)');
setTimeout(function(){
$('.testi').css('transition', '1.5s ease');
x = x - 100;
}, 1500);
}, pause, 100);
Thank you #Jonathan Halpern you make me think about that in a different way so I managed to solve it just made some changes
var $post = $('.testi');
var x = -100;
var pause = 4000;
setIntervalX(function () {
if (x == -400){
$post.css('transition', '0s ease');
$post.css('transform', 'translateX(0)');
x = -100;
};
setTimeout(function(){
$('.testi').css('transition', '1s ease');
$post.css('transform', 'translateX(' + x + '%)');
x = x - 100;
}, 150)
}, pause, 100);

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/

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/

How to call a function with a delay

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

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