I'm trying to make random images move upwards then return to their original position.
<script>
var looper = setInterval(animateAll, 2000, myArray);
function animateAll(myArray) {
// Gets a random image ID
var randomId = myArray[Math.floor(Math.random()*myArray.length)];
// Make that random icon bounce
bounce(randomId) ;
}
function bounce(randomId) {
var icon = document.getElementById(randomId)
var top = icon.offsetTop;
setTimeout ( icon.style.top = top-20 + "px", 500) ;
setTimeout ( icon.style.top = top + "px", 500) ;
}
</script>
Both setTimeout lines work fine. With only one line, well the images will move without returning to their original position. With both lines, images don't move at all, probably because there's no delay between each.
Thanks for your help !
The problem is that you're executing the code in your setTimeout calls immediately. You're effectively saying "execute the result of setting the icon.style.top = whatever in 500 milliseconds" ... which does nothing.
Try this instead:
icon.style.top = top-20 + "px";
setTimeout ( function() { icon.style.top = top + "px"; }, 500) ;
... and I just blew 15 minutes on this, lol:
var steps = 7;
var increment = (Math.PI) / steps;
var bounceHeight = 20;
function doStep(icon, start, major, minor, height) {
if (minor == steps) {
major--;
height /= 2;
minor = 0;
icon.style.top = start;
}
if (major < 0) {
return;
}
if (minor < steps) {
pos = Math.sin((minor + 1) * increment);
icon.style.top = (start - height * pos) + "px";
setTimeout( function() { doStep(icon, start, major, minor + 1, height); }, 500/steps );
}
}
function bounce(randomId) {
var icon = document.getElementById(randomId)
var top = icon.offsetTop;
setTimeout ( function() { doStep(icon, top, 3, 0, bounceHeight); }, 500/steps ) ;
}
How about moving the image up immediately when you call bounce and then returning it to the original position after a timeout?
function bounce(randomId) {
var icon = document.getElementById(randomId)
var top = icon.offsetTop;
icon.style.top = top-20 + "px";
setTimeout ( icon.style.top = top + "px", 500) ;
}
Related
I would like you to help me for a thing here, for a function to increase and then decrease SVG shape when it hits limit.
It should go from 3 to 6 and then 6 to 3 and so on... but instead it goes from 3 to 6 and then 6 to minus infinite. And I don't understand why.
Here is my code :
var size = 3;
var sizeManager = 1;
function increaseAnimation(el){
var elem = document.getElementById(el);
elem.style.transform = "scale("+size+")";
timer = setTimeout('increaseAnimation(\''+el+'\',3000)');
size=size+0.005*sizeManager;
if(size >= 6){
sizeManager=sizeManager*-1;
}
if (size <= 3){
sizeManager=sizeManager*+1;
}
}
Your weird setTimeout implementation, with bound was broken.
There's also the issue that your sizeManager is not properly reflecting:
function increaseAnimation(id, interval) {
var size = 1;
var velocity = 0.05;
var elem = document.getElementById(id);
function iterate() {
elem.style.transform = "scale(" + size + ")";
size += velocity;
if (size > 2 || size < 1) {
velocity *= -1; // velocity reflected
}
}
var timer = setInterval(iterate, interval);
return function stop() {
clearInterval(timer)
}
}
I also added a stop function which you can call at a later point.
var stopper = increaseAnimation("content", 16);
setTimeout(stopper, 5000);
The error is with the line sizeManager=sizeManager*+1; Multiplying a number by one doesn't change it. You basically want to toggle sizeManager between -1 and +1, and you can do so by multiplying by -1, regardless of whether it is currently negative or positive.
I've tested this code and it seems to work:
var size = 3;
var sizeManager = 1;
function increaseAnimation(el) {
var elem = document.getElementById(el);
elem.style.transform = "scale(" + size + ")";
timer = setTimeout("increaseAnimation('" + el + "', 3000)");
size += 0.005 * sizeManager;
if (size >= 6 || size <= 3) {
sizeManager *= -1;
}
}
Full HTML for a POC demo at: https://pastebin.com/GW0Ncr9A
Holler, if you have questions.
function Scaler(elementId, minScale, maxScale, deltaScale, direction, deltaMsecs) {
var scale = (1 == direction)?minScale:maxScale;
var timer = null;
function incrementScale() {
var s = scale + deltaScale*direction;
if (s < minScale || s > maxScale) direction *= -1;
return scale += deltaScale*direction;
};
function doScale(s) {
document.getElementById(elementId).style.transform = 'scale(' + s + ')';
};
this.getDeltaMsecs = function() {return deltaMsecs;};
this.setTimer = function(t) {timer = t;};
this.run = function() {doScale(incrementScale());};
this.stop = function() {
clearInterval(timer);
this.setTimer(null);
};
};
var scaler = new Scaler('avatar', 3, 6, .05, 1, 50);
function toggleScaler(ref) {
if ('run scaler' == ref.value) {
ref.value = 'stop scaler';
scaler.setTimer(setInterval('scaler.run()', scaler.getDeltaMsecs()));
}
else {
scaler.stop();
ref.value = 'run scaler';
}
};
I have an an image moving across the screen and out of viewport, when the image reaches a particular absolute position (right: - 200), I want to trigger the below animation. I am relatively new to programming, not sure how to track when a particular function is done so that I can trigger the below animation.
var $startLessonButton = $('.startLessonButtonUp');
$startLessonButton.mouseup(function() {
$(this).addClass('animated slideInLeft');
});
---------
var movingOutAnimationCounter = 2;
var movingOutCurrentPosition = window.innerWidth / 2 - 200
function moveTrumpOut() {
movingOutCurrentPosition -= 2;
trumpyWrapper.style.right = movingOutCurrentPosition + 'px';
if (movingOutAnimationCounter < 9 ) {
trumpy.src = '../images/trump_walking_out_' + movingOutAnimationCounter + '.png';
movingOutAnimationCounter += 1;
} else {
movingOutAnimationCounter = 1;
trumpy.src = '../images/trump_walking_out_' + movingOutAnimationCounter + '.png';
}
if (movingOutCurrentPosition > -200 ) {
requestAnimationFrame(moveTrumpOut);
}
}
All the best!
If you know time, when moving element is hidden, you can use this function:
setTimeout(function(){ $('.elem').addClass("animCssClass") }, 1000);
Last parameter, in this example: 1000 is time in ms, when function inside should execute. Run this function on mouseup when you adding class to moving element.
There are 4 horses on my track. https://i.imgur.com/xKFTZ8a.png
I press start and the horses are supposed to complete a lap. I have managed to make them go around the first corner and make them stop at the second corner like so https://i.imgur.com/4uwrBiN.png
Heres my code for the white horse, my problem is that the functions are calling each other constantly and due to this I am unable to go around the second corner due to
positionTop >= window.innerHeight * 0.84 - 50
from horse1 function running and preventing the horse from going left.
var interval = 0;
function startRace() {
var raceTimer = setInterval(100);
var raceActive = true;
loop();
}
function loop() {
interval = setInterval(horse1, 10);
interval = setInterval(horse2, 10);
interval = setInterval(horse3, 10);
interval = setInterval(horse4, 10);
}
function horse1() {
var horse1 = document.getElementById('horse1');
var positionLeft = horse1.offsetLeft;
var positionTop = horse1.offsetTop
horse1.className = 'horse runRight'
if (positionLeft >= window.innerWidth * 0.84 - 50) {
horse1down();
} else {
horse1.style.left = positionLeft + 1 + 'px';
}
}
function horse1down() {
var horse1 = document.getElementById('horse1');
var positionTop = horse1.offsetTop;
horse1.className = 'horse runDown'
if (positionTop >= window.innerHeight * 0.85 - 50) {
horse1left()
} else {
horse1.style.top = positionTop + 1 + 'px';
}
}
function horse1left() {
var horse1 = document.getElementById('horse1');
var positionLeft = horse1.offsetLeft
horse1.style.left = positionLeft - 1 + 'px';
horse1.className = 'horse runLeft'
}
function myLoadFunction() {
var startButton = document.getElementById('start');
startButton.addEventListener('click', startRace);
}
document.addEventListener('DOMContentLoaded', myLoadFunction);
What I have tried:
I have tried clear intervals but I might be doing them wrong.
function horse1down() {
var horse1 = document.getElementById('horse1');
var positionTop = horse1.offsetTop;
horse1.className = 'horse runDown'
if (positionTop >= window.innerHeight * 0.85 - 50) {
horse1left()
clearInterval(interval);
interval = setInterval(horse1, 10);
} else {
horse1.style.top = positionTop + 1 + 'px';
}
}
You are overwriting variable interval.Create an array with 4 different intervals and you will be able to clear them separately.
In general its better to use setTimeout insead of setInterval. You can easily rewrite setInterval function to safer setTimeout. setInterval doesn't care whether the callback is still running or not.
In some cases, the function might need longer than the interval time to finish execution. What would happen is that you'll end up with a bunch of queued requests that may not necessarily return in order.
This has been asked before and I got my code running.
The problem is with some weird viewport sizes the script seems to freeze.
There is nothing you can do but kill the tab.
I tried to script some backup that will kill the loop if its frozen, but it does not seem to get the job done.
Can anyone tell me whats wrong? Or show me an error in the script in general thats causing the freeze?
Thats the site where the code is running:
http://unkn0wn3d.com
JS Code is eithere there:
http://unkn0wn3d.com/css/pos.js
or here:
var pos = function(){
var containerW = $("article").width();
var containerH = $("article").height();
var langH = parseInt($( ".languages" ).position().top + $( ".languages" ).height());
var langW = parseInt($( ".languages" ).position().left + $( ".languages" ).width());
var creditW = parseInt($( ".credit" ).position().left - $(".link:first").width() + 15);
var positions = [];
var froze = false;
setTimeout(function(){froze=true;}, 2000)
$('.link').each(function() {
var coords = {
w: $(this).outerWidth(true)+5,
h: $(this).outerHeight(true)+5
};
var success = false;
while (!success)
{
coords.x = parseInt(Math.random() * (containerW-coords.w));
coords.y = parseInt(Math.random() * (containerH-coords.h));
var success = true;
$.each(positions, function(){
if (froze){return false;}
if (
(coords.x <= langW &&
coords.y <= langH) ||
(coords.x >= creditW &&
coords.y <= langH) ||
(coords.x <= (this.x + this.w) &&
(coords.x + coords.w) >= this.x &&
coords.y <= (this.y + this.h) &&
(coords.y + coords.h) >= this.y)
)
{
success = false;
}
});
}
positions.push(coords);
$(this).css({
top: coords.y + 'px',
left: coords.x + 'px',
display: 'block'
});
})};
var waitForFinalEvent = (function () {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
$(document).ready(
pos()
);
$(window).resize(function () {
waitForFinalEvent(function(){pos();}, 500, "resize");
});
You have 2 problems. I don't see where you are doing it, but the size of your A.link elements is being controlled only by the height of the viewport. So if the viewport is tall and narrow, then the links are large, and it's simply impossible to fit them all.
The second problem is that if the links can't be placed your code just keeps trying forever. The timer will never fire because the main script is still busy running. Rather than just do
while (!success)
it would be better to do a limited number of attempts:
var success = false;
for (var attempt = 0; !success && attempt < 50; attempt++)
{
....
}
By limiting the number of tries it will stop it freezing, even if the links are left overlapping. Then you can remove froze and the timer.
Even better would be to introduce a tolerance as the number of attempts increases - so they are allowed to overlap a little bit.
Your while loop never terminates since inside it you wrote var success = true
You redefined your success variable again by using var, so now you have 2 instances of success and the first one is never set to true so the loop never terminates. Try removing var from var success = true
I'm trying to gradually increase the elements of 2 id's in javascript using a Timeout. I can get one working but when trying to call another element into the same function it only does one iteration then crashes after the first recursive call.
I'm passing two id's for the elements. and I want the left element to gradually increase while the right element gradually increases in width.
Heres what ive got
function grow(elementL, elementR)
{
var htL = parseInt(document.getElementById(elementL).style.width,10);
var htR = parseInt(document.getElementById(elementR).style.width,10);
var movementL = htL + 5;
var movementR = htR - 5;
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
if (movementL > 1000) {
clearTimeout(loopTimer);
return false;
}
var loopTimer = setTimeout('grow(\''+elementL+','+elementR+'\')',50);
}
You could simplify this (removing the script-generation) by using setInterval -- this repeats the function call until you cancel it.
function grow(elementL, elementR)
{
var loopTimer = setInterval(function() {
if (!growStep(elementL, elementR)) {
clearInterval(loopTimer);
}
}, 50);
}
function growStep(elementL, elementR) {
var htL = parseInt(document.getElementById(elementL).style.width,10);
var htR = parseInt(document.getElementById(elementR).style.width,10);
var movementL = htL + 5;
var movementR = htR - 5;
document.getElementById(elementL).style.width = movementL + 'px';
document.getElementById(elementR).style.width = movementR + 'px';
if (movementL > 1000) {
return false;
}
return true;
}
(Fiddle)
Edit
Yeah, I guess the only problem with the OP code is that it passes a string to setTimeout, rather than the function itself:
var loopTimer = setTimeout(function() {
grow(elementL, elementR);
},50);
setTimeout('grow(\''+elementL+','+elementR+'\')',50)
would need to be
setTimeout('grow(\''+elementL+'\',\''+elementR+'\')',50)
// ^^ ^^
to work. But don't do that. Pass a function expression to setTimeout:
setTimeout(function() {
grow(elementL, elementR);
}, 50)