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);
Related
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/
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();
});
Everything was going smoothly until now. I want to have this hor() function reverse after 20 seconds. The original hor() function grabs an image offscreen and moves it horizontally from the left to the center of the page. I'd like to create a function that does the opposite after 20 seconds. The "after 20 seconds" part is giving me the most grief. If you could show me what a new function would look like or an 'else' addition to the current function that would be great. Thanks.
<script language="JavaScript" type="text/JavaScript">
var x = -500;
var y = 100;
function hor(val) {
if (x <= 500){
x = x + val;
document.getElementById("pos").style.left = x + "px";
setTimeout("hor(5)", 10);
}
}
</script>
<style type="text/css">
<!--
#pos {
position: absolute;
left: -500px;
top: 100px;
z-index: 0;
}
</style>
<body onLoad="setTimeout('hor(5)',5000)">
<div id="pos">
<img src="image.jpg">
</div>
Perhaps you could try changing the script to this:
// Define variables
var x = -500,
y = 100,
direction = 1;
// Function which moves "pos" element
function hor(val) {
// Move by specified value multiplied by direction
x += val * direction;
if(x > 500){
x = 500;
// Reverse direction
direction = -1;
} else if(x < -500){
x = -500;
// Reverse direction, once again
direction = 1;
}
// Move element
document.getElementById("pos").style.left = x + "px";
// Continue loop
setTimeout("hor("+val+")", 10);
}
This code will continue moving the pos element by the specified value until x greater than 500, at which point it will switch direction, then continue until x reaches -500, and so on.
EDIT:
This code will fix that issue with 20 seconds (I had thought that the 500 pixel thing computed to 20 seconds, lol).
// Define variables
var x = -500,
y = 100,
direction = 1;
firstCall = true;
timeElapsed = 0;
// Function which moves "pos" element
function hor(val) {
// Don't let the first call count!
if(!firstCall)timeElapsed += 10;
else firstCall = false;
if(timeElapsed >= 2000){
// Reverse direction
direction *= -1;
timeElapsed = 0;
}
// Move by specified value multiplied by direction
x += val * direction;
// Move element
document.getElementById("pos").style.left = x + "px";
// Continue loop
setTimeout("hor("+val+")", 10);
}
Try this. Here the img is moved horizontally and after sometime it is reverted back to its original position.
<script>
var x = -500;
var y = 100;
var op;
function hor(val) {
if (x <= 500 && x>=-500) {
x = x + val;
document.getElementById("pos").style.left = x + "px";
setTimeout(function(){hor(val);},10);
}
}
$(document).ready(function(){
setTimeout(function(){hor(5);},1000);
setInterval(function(){
setTimeout(function(){hor(-5);},1000);
},2000);
});
</script>
I have changed the timings for testing purpose only, you can change it back.
I was trying to create a auto slide for the slider using setInterval. It works like a charm when there's only one slider.
When there are 2 slider, the first slider wont work, and the second slider will slide faster, because there will be 2 setInterval and both are sliding the second slider. Anyway to make sure each setInterval slide their own slider?
var autoSlideTimer = 5;
var autoslide = setInterval(function () {
if (autoSlideTimer == 0) {
var slideMargin = offsetMarginLeft - width;
if (-slideMargin == (width * totalImages)) {
offsetMarginLeft = width;
displayImage = 0;
}
slider.style.marginLeft = (offsetMarginLeft - width) + 'px';
displayImage += 1;
pagination = element.getElementsByTagName('ul')[0];
pagination.innerHTML = paginate;
pagination.getElementsByTagName('li')[displayImage - 1].setAttribute("class", "displayed");
slider = element.getElementsByTagName('div')[0];
offsetMarginLeft = parseInt(slider.style.marginLeft.replace('px', ''));
autoSlideTimer = 5;
} else {
autoSlideTimer--;
}
}, 1000);
thanks
I work it out with another way, although is working but doesnt seems to be the perfect way
var event = new Event('build');
// Listen for the event.
element.addEventListener('build', function (e) {
function timeoutLoop()
{
setTimeout(function(){
if(autoSlideTimer == 0)
{
var slideMargin = offsetMarginLeft - width;
if(-slideMargin == (width * totalImages))
{
offsetMarginLeft = width;
displayImage = 0;
}
slider.style.marginLeft = (offsetMarginLeft - width) + 'px';
displayImage += 1;
pagination = element.getElementsByTagName('ul')[0];
pagination.innerHTML = paginate;
pagination.getElementsByTagName('li')[displayImage - 1].setAttribute("class", "displayed");
offsetMarginLeft = parseInt(slider.style.marginLeft.replace('px', ''));
autoSlideTimer = 5;
}else
{
autoSlideTimer--;
}
timeoutLoop();
},1000);
}
timeoutLoop();
}, false);
// Dispatch the event.
element.dispatchEvent(event);
At first, I used setInterval inside, yet the slider will be overwritten. But setTimeout is ok.
I'm trying to create an loading icon by moving the css 'background-position' of an image in a loop:
$('#LoginButton').click(function () {
var i = 1, h = 0, top;
for (i = 0; i <= 12; i++) {
h = i * 40;
top = h + 'px';
$('#ajaxLoading').css('background-position', '0 -' + top).delay(800);
}
});
The problem here is that it runs to fast so I don't se the 'animation' of the moving background.
So I added jquerys delay(), but:
delay(800) is not working because delay() only works in jquery animation effects and .css() is not one of those.
How to delay this loop?
I'd suggest using jQuery timer plugin: http://jquery.offput.ca/js/jquery.timers.js
$('#LoginButton').click(function () {
var times = 13;
var delay = 300;
var h = 0, top;
$(document).everyTime(delay, function(i) {
top = h + 'px';
$('#ajaxLoading').css('background-position', '0 -' + top);
h += 40;
}, times);
});
In case you don't want any plugins, use setInterva/clearInterval:
$('#LoginButton').click(function () {
var delay = 300;
var times = 13;
var i = 0, h = 0, top;
doMove = function() {
top = h + 'px';
$('#ajaxLoading').css('background-position', '0 -' + top);
h += 40;
++i;
if( i >= times ) {
clearInterval( interval ) ;
}
}
var interval = setInterval ( "doMove()", delay );
});
Have you looked at using animate() instead of css()? I'm not 100% sure I understand what you're trying to accomplish, so this is kinda a shot in the dark.
http://api.jquery.com/animate/
Chrome, Safari and IE3+ should support background-position-y, so if you're targeting these specific browser, using jquery you could just make a timed animation() on backgroundPositionY property - http://snook.ca/archives/html_and_css/background-position-x-y
(On Firefox the effect won't work)
You can use setTimeout() and clearTimeout() functions in order to accomplish that.
IE:
var GLOBAL_i = 0;
function doAnimation() {
var h = GLOBAL_i * 40;
var top = h + 'px';
$('#ajaxLoading').css('background-position', '0 -' + top);
if (GLOBAL_i < 12) {
GLOBAL_i++;
t=setTimeout(doAnimation, 800);
}
}
$('#LoginButton').click(function () {
doAnimation()
});