Javascript setTimeout, Loops and Closure - javascript

The following code has me confused. My goal is to fade an HTML element from one opacity level to another, over a period of time. Below is my dimScreen() method, used to create a darkened overlay and fade it in.
var overlay;
function dimScreen()
{
if(!overlay)
{
overlay = document.createElement('div');
overlay.setAttribute('id', 'overlay');
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.zindex = '1000';
overlay.style.background = '#000013';
overlay.style.position = 'fixed';
overlay.style.left = '0';
overlay.style.top = '0';
overlay.style.opacity = '.0';
document.body.appendChild(overlay);
fade('overlay', 0, 75, 200);
}
}
Here is my working fade function:
function fade(eID, startOpacity, stopOpacity, duration)
{
var speed = Math.round(duration / 100);
var timer = 0;
if (startOpacity < stopOpacity)
{ // fade in
for (var i=startOpacity; i<=stopOpacity; i++)
{
setTimeout("setOpacity('"+eID+"',"+i+")", timer * speed);
timer++;
} return;
}
for (var i=startOpacity; i>=stopOpacity; i--)
{ // fade out
setTimeout("setOpacity('"+eID+"',"+i+")", timer * speed);
timer++;
}
}
And my working setOpacity:
function setOpacity(eID, opacityLevel)
{
var eStyle = document.getElementById(eID).style;
eStyle.opacity = opacityLevel / 100;
eStyle.filter = 'alpha(opacity='+opacityLevel+')';
}
I would like to, however, change my fade() function to user a closure in the form of:
setTimeout(function(){setOpacity(eID,i)}, timer * speed);
I could then pass in the actual overlay div, instead of the id 'overlay'. When I do this, however, rather than animating a gradual fade-in of the overlay div, it just goes right to the last opacity value with no transition. Why does this happen?
I have a feeling this is something simple that I am missing because I've been looking at it for so long. Any help would be appreciated!

It's too late and still too hot to think much here right now. (2.30am, 28°C)
Forgive me if my explanation falls short of expectations.
Basically, because you construct text strings to pass to setTimeout, each call gets the correct value for i. Since to pass an actual element, you can't use the string trick, you end up using the same value of i for each call to setOpacity.
As your question title indicates you understand, you need to use closures to get it to work right. I can't find(only followed 2 or 3 links) a good tute/S.O question that explains it in a way that seems relevant and clear.
Hope the code will be of use.
var overlay;
function dimScreen()
{
if(!overlay)
{
overlay = document.createElement('div');
overlay.setAttribute('id', 'overlay');
overlay.style.width = '100%';
overlay.style.height = '100%';
overlay.style.zindex = '1000';
overlay.style.background = '#000013';
overlay.style.position = 'fixed';
overlay.style.left = '0';
overlay.style.top = '0';
overlay.style.opacity = '.0';
document.body.appendChild(overlay);
myFade(overlay, 0, 75, 2000);
}
}
function myFade(element, startOpacity, stopOpacity, duration)
{
var speed = Math.round(duration / 100);
var timer = 0;
if (startOpacity < stopOpacity)
{ // fade in
for (var i=startOpacity; i<=stopOpacity; i++)
{
(
function()
{
var myI = i;
setTimeout(function(){mySetOpacity(element,myI)}, timer * speed);
}
)()
timer++;
}
}
else
for (var i=startOpacity; i>=stopOpacity; i--)
{ // fade out
for (var i=startOpacity; i<=stopOpacity; i++)
{
(
function()
{
var myI = i;
setTimeout(function(){mySetOpacity(element,myI)}, timer * speed);
}
)()
timer++;
}
}
}
function mySetOpacity(el, opacityLevel)
{
var eStyle = el.style;
eStyle.opacity = opacityLevel / 100;
eStyle.filter = 'alpha(opacity='+opacityLevel+')';
}

Related

Prevent double images in function using Math.random

I have a function that adds random images to my divs that disappear over time and create a mouse trail. My issue is: there are double images.
I'd like to add something that checks if the background url is already located on the page and if that's the case, skips to the next in the array and check it again until until it comes across one that is not there. So like a loop that refreshes every time a 'trail' is being created.
Maybe I am asking for something that won't work? What if all the images are already on the page? I don't really have an answer for it and I also don't have an idea how to solve that problem yet.
For now I tried adding a counter that checks the usedImages and counts them, but it seems to have flaws and I am unsure where to look or how to fix it. Does anyone have any tips on how to do this? Is it even possible?
My fiddle
var bgImages = new Array(
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/schraegluftbild-1024x725.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/pikto-608x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/lageplan-945x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhausen-EG-Grundriss-913x1024.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/05/Jettenhauser-Esch-Modell-2-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/DSCN3481-1024x768.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2019/07/zoom-in-3_ASTOC-1024x683.jpg",
"https://www.studiourbanestrategien.com/wordpress/wp-content/uploads/2016/07/IMG_1345-1024x768.jpg"
);
const numberOfImages = 10;
const timesPerSecond = .1;
var usedImages = {};
var usedImagesCount = 0;
function preloadImages(images) {
for (i = 0; i < images.length; i++) {
let l = document.createElement('link')
l.rel = 'preload'
l.as = 'image'
l.href = images[i]
document.head.appendChild(l);
}
}
function animate(e) {
var image = document.createElement('div');
image.classList.add('trail');
var sizew = 200;
var sizeh = 200;
image.style.transition = '3s ease';
image.style.position = 'fixed';
image.style.top = e.pageY - sizeh / 2 + 'px';
image.style.left = e.pageX - sizew / 2 + 'px';
image.style.width = sizew + 'px';
image.style.height = sizeh + 'px';
var random = Math.floor(Math.random() * (bgImages.length));
if (!usedImages[random]) {
image.style.backgroundImage = "url(" + bgImages[random] + ")";
usedImages[random] = true;
usedImagesCount++;
if (usedImagesCount === bgImages.length) {
usedImagesCount = 0;
usedImages = {};
}
} else {
animate(e);
}
console.log(usedImages);
console.log(usedImagesCount);
image.style.backgroundSize = 'cover';
image.style.pointerEvents = 'none';
image.style.zIndex = 1;
document.body.appendChild(image);
//opacity and blur animations
window.setTimeout(function() {
image.style.opacity = 0;
image.style.filter = 'blur(20px)';
}, 40);
window.setTimeout(function() {
document.body.removeChild(image);
}, 2100);
};
window.onload = function() {
preloadImages(bgImages);
var wait = false;
window.addEventListener('mousemove', function(e) {
if (!wait) {
wait = true;
setTimeout(() => {
wait = false
}, timesPerSecond * 800);
animate(e);
}
});
};

GIF image position animation using JavaScript

I'm trying to change image position using JavaScript using my code but for some reason it doesn't work. Can someone explain the reason.
var walk, isWaveSpawned = true;
var walkers = [];
function start()
{
walk = document.getElementById("walk");
draw(); //Animation function
}
function draw()
{
if(isWaveSpawned) //Generate a wave of 5 "walkers"
{
isWaveSpawned = false;
for(var i = 0; i < 5; i++
walkers.push(new createWalker());
}
for(var o = 0; o < walkers.length; o++) //Add 1px to x position after each frame
{
walkers[o].x += walkers[o].speed;
walkers[o].image.style.left = walkers[o].x;
walkers[o].image.style.top = walkers[o].y;
}
requestAnimationFrame(draw);
}
function createWalker()
{
this.x = 0;
this.y = 100;
this.speed = 1;
this.image = walk.cloneNode(false); //Possible cause of issue
}
<!DOCTYPE html>
<html>
<body onload="start()">
<img id="walk" src="https://i.imgur.com/ArYIIjU.gif">
</body>
</html>
My GIF image is visible in top left corner but doesn't move.
P.S. Added a HTML/JS snippet but it outputs some errors while in my end these errors are not seen.
First let's modify the way you're cloning the gif - get rid of this line:
this.image = walk.cloneNode(false);
and insert this:
this.image = document.createElement("img");
This will create a fresh empty HTML image element.
Now assign it's .src property the source of your gif:
this.image.src=document.getElementById("walk").src;
and set the CSS position property to absolute:
this.image.style="position:absolute;";
finally add this new image element to the body using:
document.body.appendChild(this.image);
If you hit run you will still not see any movement because there's still a little fix to do!
Find this line:
walkers[o].image.style.left = walkers[o].x;
and change it to this:
walkers[o].image.style.left = walkers[o].x + "px";
var walk, isWaveSpawned = true;
var walkers = [];
function start() {
walk = document.getElementById("walk");
draw(); //Animation function
}
function draw() {
if (isWaveSpawned) //Generate a wave of 5 "walkers"
{
isWaveSpawned = false;
for (var i = 0; i < 5; i++)
walkers.push(new createWalker());
}
for (var o = 0; o < walkers.length; o++) //Add 1px to x position after each frame
{
walkers[o].x += walkers[o].speed;
walkers[o].image.style.left = walkers[o].x + "px";
walkers[o].image.style.top = walkers[o].y + "px";
}
requestAnimationFrame(draw);
}
function createWalker() {
this.x = 0;
this.y = 100;
this.speed = 1;
this.image = document.createElement("img");
this.image.src = document.getElementById("walk").src;
this.image.style = "position:absolute;";
document.body.appendChild(this.image);
}
start();
<body>
<img id="walk" src="https://i.imgur.com/ArYIIjU.gif">
</body>

Make a multiple objects with javascript and png

I'm trying to get a spaceship animation scene with a group of comets going down.
//Create a comet div with img attached to it
var cometScene = function(spaceNo){
var b = document.createElement('div');
b.id = 'cometio';
var cometImage = document.createElement('img');
cometImage.setAttribute('src', 'images/comet1.png');
b.appendChild(cometImage);
document.getElementById('wrap').appendChild(b);
}
//Comet move
function cometMove(){
var comet = document.getElementById('cometio');
var pos = 0;
var interval = setInterval(scene, 3);
function scene(){
if (pos === 1000){
clearInterval(interval);
} else {
pos++;
comet.style.top = pos + 'px';
comet.style.left = pos + 'px';
}
}
setInterval(scene, 3)
}
But when I call a function cometScene(3) I'm not getting 3 similar objects. Also how these objects can be allocated across the whole screen as this is just a single div.
function main(){
var w = document.createElement('div');
w.id = 'wrap';
document.querySelector('body').appendChild(w);
astronautScene();
cometScene();
shaceshipScene();
cometMove();
astronautMove();
}
This it what I would do:
Give the comets a class instead of an id, because there can be more of them.
Because there can be multiple use a loop to iterate through them
To give them the ability to move freely, they need to have position:absolute or something similiar
Don't use the same variable for the position of all comets, because they could be in different positions
To get the current position just parse the currect top and left value to a Number
//Create a comet div with img attached to it
var cometScene = function(spaceNo) {
var b = document.createElement('div');
b.className = 'cometio';
var cometImage = document.createElement('img');
cometImage.setAttribute('src', 'images/comet1.png');
b.appendChild(cometImage);
document.getElementById('wrap').appendChild(b);
}
//Comet move
function cometMove() {
var comets = document.getElementsByClassName('cometio');
for (let i = 0; i < comets.length; i++) {
const comet = comets[i];
comet.style.top = "0px";
comet.style.left = "0px";
comet.style.position = "absolute";
var interval = setInterval(scene, 3);
function scene() {
let x = parseInt(comet.style.left);
let y = parseInt(comet.style.top);
if (x === 1000) {
clearInterval(interval);
} else {
comet.style.top = (1 + x) + 'px';
comet.style.left = (1 + y) + 'px';
}
}
}
//setInterval(scene, 3)don't start the interval twice
}
function main() {
var w = document.createElement('div');
w.id = 'wrap';
document.querySelector('body').appendChild(w);
//astronautScene();
cometScene();
//shaceshipScene();
cometMove();
//astronautMove();
}
main();

Expand the width of an element with a setTimeOut loop

I am trying to create a simple javascript animation that will expand the width of an element from 0px to a specified width. Although this is probably a pretty elementary problem for some, I just can't seem to figure out what I am doing wrong. Instead of the loop running and expanding the div as desired I am only able to expand the div by repeatedly firing the function manually.
Fiddle
Current js code:
var el = document.getElementById('h');
var btn = document.getElementById('button1');
var oswidth = el.offsetWidth;
var target_width = 100;
btn.onclick = function grow() {
var loop = setTimeout('grow(\'' + el + '\')', 20);
if (oswidth < target_width) {
oswidth += 5;
} else {
clearTimeout(loop);
}
el.style.width = oswidth + 'px';
}
And as always, thank you in advance!
Try this code.fiddle-https://jsfiddle.net/L8kLx7d2/
var el = document.getElementById('h');
var btn = document.getElementById('button1');
var oswidth = el.offsetWidth;
var target_width = 100;
var loop;
function grow() {
if (oswidth < target_width) {
oswidth += 5;
} else {
clearInterval(loop);
}
el.style.width = oswidth + 'px';
}
btn.onclick=function(){
loop=setInterval(grow, 1000)};
Try this:
var el = document.getElementById('h');
var btn = document.getElementById('button1');
var oswidth = el.offsetWidth;
var target_width = 100;
btn.onclick = function grow() {
if (oswidth < target_width) {
oswidth += 5;
el.style.width = oswidth + 'px';
setTimeout(grow, 20);
}
}
I'll leave it to you to puzzle over the differences.
You can call the grow function in setInterval
JS:
var el = document.getElementById('h');
var btn = document.getElementById('button1');
var oswidth = el.offsetWidth;
var target_width = 100;
function grow() {
var loop = setTimeout('grow(\'' + el + '\')', 20);
if (oswidth < target_width) {
oswidth += 5;
} else {
clearTimeout(loop);
}
el.style.width = oswidth + 'px';
}
setInterval(grow, 1000);
Demo: http://jsfiddle.net/lotusgodkk/jeq834de/1/
There are three solutions. The first is using recursive setTimeout:
function grow(time) {
if (oswidth < target_width) {
oswidth += 5;
el.style.width = oswidth + 'px';
setTimeout(function() {grow(time);}, time);
}
}
The second is to use setInterval as described in the answer of K K.
The third is my personal favorite, using the transition css attribute.

Canvas fade in/out functions not working as expected

So I have these functions to fade a canvas in and out that aren't working the way I expect them to. Here's what I'm working with at the moment:
function fade_out ()
{
var canvas = document.getElementById("builder");
var context = canvas.getContext('2d');
console.log(context.globalAlpha);
context.globalAlpha -= 0.01;
if(context.globalAlpha > 0)
{
setTimeout(fade_out, 5);
}
}
function fade_in ()
{
var canvas = document.getElementById("builder");
var context = canvas.getContext('2d');
context.globalAlpha += 0.01;
if(context.globalAlpha < 1)
{
setTimeout(fade_in, 5);
}
}
My intent was to make it a half second fade. What I ended up with was it just blinking in and out in a flash. The console.log in the first function tells me it's not even close to working the way I expect it to. What went wrong here?
EDIT: There seems to be an endless loop going, and the context.globalAlpha is getting into 20 significant digits, even though I didn't use numbers like that.
function fade_in() {
setTimeout( function() {
var cn = document.getElementById("builder");
var ct = cn.getContext('2d').globalAlpha;
ct += 0.02;
if(ct >= 1) {
ct=1;
}
if (ct < 1) {
fade_in();
}
else {
return false;
}
}, 30);
}
function fade_out() {
setTimeout( function() {
var cn = document.getElementById("builder");
var ct = cn.getContext('2d').globalAlpha;
ct -= 0.02;
if(ct <= 0) {
ct=0;
}
if (ct > 0) {
fade_out();
}
else {
return false;
}
}, 30);
}

Categories