Expand the width of an element with a setTimeOut loop - javascript

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.

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

How do I loop through an array of buttons and only continue looping if the user clicks the next button in the array

Not sure if this is exactly the correct approach for this but I have an array of buttons that spawn on the screen and after a few seconds it changes location and I have to click the buttons in the order they appeared initially.
Following is the code:
let arrayButtons = [];
let goButton = document.getElementById("inputButton");
function Buttons(color, height, width, top, left, order) {
this.order = order;
this.btn = document.createElement("button");
this.btn.style.backgroundColor = color;
this.btn.style.height = height;
this.btn.style.width = width;
this.btn.style.position = "absolute";
document.body.appendChild(this.btn);
this.setLocation = function(top, left) {
this.btn.style.top = top;
this.btn.style.left = left;
};
this.setLocation(top, left);
}
function createButtons(numOfButtons) {
console.log(numOfButtons);
let color;
let heightVal;
let widthVal;
let top;
let left;
let currentButton;
for (let i = 0; i < numOfButtons; i++) {
color = "#" + genRandomColor();
heightVal = "60px";
widthVal = "120px";
let x = window.innerWidth - 100;
let y = window.innerHeight - 100;
top = 90 + "px";
left = i * 120 + "px";
currentButton = new Buttons(color, heightVal, widthVal, top, left, i);
arrayButtons.push(currentButton);
}
}
function genRandomColor() {
let randomColor = Math.floor(Math.random() * 16777215).toString(16);
return randomColor;
}
function change() {
setTimeout(function() {
let x = window.innerWidth - 100;
let y = window.innerHeight - 200;
for (let i = 0; i < arrayButtons.length; i++) {
randomX = Math.floor(Math.random() * x + 50);
randomY = Math.floor(Math.random() * y + 50);
arrayButtons[i].setLocation(
randomX + 'px',
randomY + 'px');
}
}, 5000);
}
function isValid(range) {
range = document.getElementById("textField").value;
if (range < 2 || range > 10) {
return false;
} else {
return true;
}
}
// idea.. if the user clicks on the button in the order of the array it works
// for the hint, just make the value equal to the index number + 1
function clickHandler() {
let minMax = isValid();
if (minMax == true) {
createButtons(document.getElementById("textField").value);
change();
} else {
window.alert("Must be between 2 and 10");
}
}
goButton.onclick = clickHandler;
<p>How Many Buttons To Create?</p>
<input id="textField" type="text">
<button type="button" id="inputButton">Go!</button>
<br>
<br>
HTML
<button class="buttonClass">1</button>
JS
let btns = document.querySelectorAll(".buttonClass");
let currentBtn = 0;
btns.forEach(function(btn, crtIndex){
btn.onclick = function(){
if(currentBtn === crtIndex){
currentBtn++;
console.log("correct");
}
};
});

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

OnClick event not fired in javascript when attached to img

I'm new to JavaScript, so this may be basic...
I'm trying to create an image dynamically and add it a event listener for "onclick". I add this img to a div.
I create the img like this:
function createNewSmiley()
{
var newSmiley = document.createElement("img");
newSmiley.src = "./smiley.jpg";
newSmiley.alt = "Smiley Image";
newSmiley.style.width = "64px";
newSmiley.style.height = "64px";
return newSmiley;
}
And then I add it to the div like using like this:
function positionNewSmiley(parent, smiley, x, y)
{
var newSmiley = createNewSmiley();
newSmiley.style.top = y + "px";
newSmiley.style.left = x + "px";
parent.appendChild(newSmiley);
}
And this is my main function:
function main(smileyCount)
{
var myDiv = document.getElementById("myDiv");
for (var i = 0; i < smileyCount;i++)
{
var x = Math.floor((Math.random() * 500));
var y = Math.floor((Math.random() * 500));
var smiley = createNewSmiley();
smiley.onclick = smileyClicked;
positionNewSmiley(myDiv, smiley, x, y);
}
}
function smileyClicked(ev) {
alert("OK");
}
But the onclick event will not fire!
however, if I add the event listener to the div - it will.
What am I doing wrong?
As mentioned in the above comment you're creating new smiley in the positionNewSmiley when you've to position the passed smiley instead :
var smiley = createNewSmiley();
smiley.onclick = smileyClicked;
positionNewSmiley(myDiv, smiley, x, y);
_________________________^^^^^^
Just use it in the position function :
function positionNewSmiley(parent, smiley, x, y)
{
smiley.style.top = y + "px";
smiley.style.left = x + "px";
parent.appendChild(smiley);
}
Hope this helps.
function createNewSmiley()
{
var newSmiley = document.createElement("img");
newSmiley.src = "http://cfile24.uf.tistory.com/image/163BB51F4BF9DF7431AB10";
newSmiley.alt = "Smiley Image";
newSmiley.style.width = "64px";
newSmiley.style.height = "64px";
return newSmiley;
}
function positionNewSmiley(parent, smiley, x, y)
{
smiley.style.top = y + "px";
smiley.style.left = x + "px";
parent.appendChild(smiley);
}
function main(smileyCount)
{
var myDiv = document.getElementById("myDiv");
for (var i = 0; i < smileyCount;i++)
{
var x = Math.floor((Math.random() * 500));
var y = Math.floor((Math.random() * 500));
var smiley = createNewSmiley();
smiley.onclick = smileyClicked;
positionNewSmiley(myDiv, smiley, x, y);
}
}
function smileyClicked(ev) {
alert("OK");
}
main(6);
<div id='myDiv'></div>
if you add the on click within the create function it will work
function createNewSmiley()
{
var newSmiley = document.createElement("img");
newSmiley.src = "./smiley.jpg";
newSmiley.alt = "Smiley Image";
newSmiley.style.width = "64px";
newSmiley.style.height = "64px";
newSmiley.addEventListener("click", smileyClicked);
return newSmiley;
}

SVG circles pulse synchronous doesn't work

I want to position one circle svg for each click I do on the object window.
My function works fine but what can I do to make circles pulse synchronous?
window.addEventListener("click",
function(event){
var myBody = document.getElementsByTagName("body")[0];
var circleDiv = document.createElement("div");
circleDiv.innerHTML = "<svg><circle cx='80' cy='80' r='20' stroke='black' fill='white' fill-opacity='0.0' /></svg>";
circleDiv.style.position = "absolute";
circleDiv.style.left = event.x+'px';
circleDiv.style.top = event.y+'px';
var direction = 5;
var radius = 20;
window.setInterval(function()
{
radius = radius + direction;
if(radius<10) direction = 5;
if(radius>50) direction = -5;
circleDiv.firstChild.firstChild.setAttribute("r",radius);
},500);
myBody.appendChild(circleDiv);
}
);
If by 'synchronus' you talk about pusle together you must split your function as is :
var direction = 1;
var radius = 20;
window.addEventListener("click",
function(event){
var myBody = document.getElementsByTagName("body")[0];
var circleDiv = document.createElement("div");
circleDiv.innerHTML = "<svg><circle cx='80' cy='80' r='" + radius + "' stroke='black' fill='white' fill-opacity='0.0' /></svg>";
circleDiv.style.position = "absolute";
circleDiv.style.left = event.x+'px';
circleDiv.style.top = event.y+'px';
myBody.appendChild(circleDiv);
}
);
window.setInterval(function()
{
var circles = document.getElementsByTagName('circle');
radius = radius + direction;
if(radius<10) direction = 1;
if(radius>50) direction = -1;
for(var i = 0; i < circles.length; i++) {
circle = circles[i];
circle.setAttribute("r",radius);
}
},20);
Here the jsFiddle
Hope it helps ;)
As you add the circles capture them in an array circles and have just one timer to update their sizes. Note I added putting your handlers in the jquery document ready function. This is good practise. Try this:
var circles = [];
var radius = 20;
var direction = 5;
jQuery(document).ready(function() {
window.addEventListener("click", function(event){
var myBody = document.getElementsByTagName("body")[0];
var circleDiv = document.createElement("div");
circleDiv.innerHTML = "<svg><circle cx='80' cy='80' r='20' stroke='black' fill='white' fill-opacity='0.0' /></svg>";
circleDiv.style.position = "absolute";
circleDiv.style.left = event.x + 'px';
circleDiv.style.top = event.y + 'px';
circles.push(circleDiv);
myBody.appendChild(circleDiv);
});
window.setInterval(function() {
radius = radius + direction;
if(radius<10) direction = 5;
if(radius>50) direction = -5;
for(var i = 0; i < circles.length; i++){
circles[i].firstChild.firstChild.setAttribute("r",radius);
}
} ,500);
});
You might want to make sure the SVG you create is using the radius value to set the starting size.

Categories