Increase Div Width with Javascript setTimeout() - javascript

How can we increase or Decrease width of a DIV using setTimeout() ??

setTimeout(function() { document.getElementById('foo').style.width = '300px' },
2000);
a related blog and spec:
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
https://developer.mozilla.org/en/DOM/window.setTimeout
If you want to increase or decrease first by getting the current width, then you can look into clientWidth():
https://developer.mozilla.org/en/DOM/element.clientWidth
or use jQuery's width():
http://api.jquery.com/width/
jQuery is becoming very popular and even used by big corporations, so you can consider using it.

<div id="progressbar" style="background-color:green; margin-top: 10px; width:0px; height:10px;"></div>
<script>
// set var to rep width of progress bar div
var dwidth=0;
// declare global variable for instance of Interval Timer so other funcs can access it.
IntervalId =0;
// grow progress bar each second
IntervalId = setInterval(function() { dwidth +=5; document.getElementById('progressbar').style.width = dwidth+'px';}, 1000);
// stop progress bar after 10 seconds
/* in real world an event handler would do this when iframe handling upload script loads response from upload */
setTimeout(function() { clearInterval ( IntervalId ); document.getElementById('progressbar').style.display='none' , 10000);
</script>

Related

particle-slider logo won't resize in Safari

I'm loading a front-end site from Wordpress using a HTML 5 Blank Child Theme. I have a logo effect using particle slider for when I have a screen size of >960px; for screen sizes <960px I have a flat logo image. It all works fine on both Firefox and Google Chrome but when I re-size between logos on Safari the page has to be refreshed manually (i.e. by pressing cmd+r) before the PS effect shows again. The code was sourced from an original question I posted here - Original Stack Q&A
Here's the javascript code I'm now using -
particle-slider.php
<?php /* Template Name: particle-slider */ ?>
<!-- particle-slider template -->
<div id="particle-slider">
<div class="slides">
<div class="slide" data-src="<?php echo home_url(); ?>/wp-content/uploads/2017/10/havoc_logohight.png"></div>
</div>
<canvas class="draw" style="width: 100%; height: 100%;"></canvas>
</div>
<script type="text/javascript">
var ps = new ParticleSlider({ 'width':'1400', 'height': '600' });
// patch nextFrame to track failure/success
var nextFrameCalled = false;
ps.oldNextFrame = ps.nextFrame;
ps.nextFrame = function () {
try {
ps.oldNextFrame.apply(this, arguments);
nextFrameCalled = true;
} catch (e) {
console.log(e);
nextFrameCalled = false;
}
};
var addEvent = function (object, type, callback) {
if (object.addEventListener) {
object.addEventListener(type, callback, false);
} else if (object.attachEvent) {
object.attachEvent("on" + type, callback);
} else {
object["on" + type] = callback;
}
};
var oldWidth = window.innerWidth;
addEvent(window, 'resize', function () {
var newWidth = window.innerWidth;
if (newWidth >= 960 && oldWidth < 960) {
console.log("Restarting particle slider " + newWidth);
ps.resize();
if (!nextFrameCalled)
ps.nextFrame(); // force restart animation
else {
// ensure that nextFrameCalled is not still true from previous cycle
nextFrameCalled = false;
setTimeout(function () {
if (!nextFrameCalled)
ps.nextFrame(); // force restart animation
}, 100);
}
}
oldWidth = newWidth;
});
</script>
<div id="logo"> <img src="<?php echo home_url(); ?>/wp-content/uploads/2017/10/havoc_logo.png"> </div>
<!-- particle-slider template -->
I need the same effect as is seen on this site here - where the logo switches from particle to static as the page is re-sized. The particle logo re-appears perfectly.
All other relevant code is linked to the original question as nothing has changed. I'm not seeing anything in the console to suggest why it's not working.
The resize event can fire multiple times, and within that event anything you put in a setTimeout will get called after the current code block has executed. It's hard to say for sure without picking apart ParticleSlider, but I think the mix of global variables (nextFrameCalled, oldWidth) and callbacks firing out of your expected order is the cause.
I think the intention is to debounce the forced restart - you want to call ParticleSlider.nextFrame() but if it's already been called you want to wait 100ms first.
Looking at the answer you've adapted for this question that appears to be a workaround for the canvas element not being visible on requestAnimationFrame - that might still not be available after 100ms or after the ParticleSlider.nextFrame() has been called multiple times in an attempt to get it to fire.
From your original question and selected answer I think you need to ParticleSlider.init() to reset the component, but the flashing you're seeing is due to the fact that it takes a while to run every time it's called. ParticleSlider.nextFrame() doesn't take as long (and uses requestAnimationFrame to avoid jank) but doesn't create the canvas on resize in Safari.
So, to fix:
Use ParticleSlider.init()
Debounce the resize event so you're not firing it lots of times
Fire it once a short delay after the user has stopped firing resize events.
Code will be something like:
var timeout = null;
window.addEventListener('resize', function() {
// Clear any existing debounced re-init
clearTimeout(timeout);
// Set up a re-init to fire in 1/2 a secound
timeout = setTimeout(function() {
ps.init();
}, 500);
});
You'll still see the flash and the delay as the component re-initialises, but only once.
I'd add that ParticleSlider has been deprecated by the authors and replaced with NextParticle - probably to fix these kinds of issues (in fact it has specific features to handle resizing). As it is a paid for component I'd suggest asking them for the help with this, as you should get your money's worth (or switch to an open source component where you can fix these bugs yourself).
So, I've finally figured this out by retracing my steps using the Q&A from before. Previously there seemed to be an issue with some of the sample links but one appears to work now - example.
I went into the page inspector and noticed a few differences between the code firing this example and the one in the actual answer that was causing the logo to flicker like a light bulb. This is the code I have now put into the wordpress site -
<script type="text/javascript">
//wait until the DOM is ready to be queried
(function() {//document.addEventListener('DOMContentLoaded', function() { //DOM-ready callback
var ps, timeout;
var img1 = new Image();
img1.src = '<?php echo home_url(); ?>/wp-content/uploads/2017/10/havoc_logohight.png';//havoc_logo_e6os2n.png';
var imgs = [ img1 ];
handlePS();
window.addEventListener('resize', function() {
//https://davidwalsh.name/javascript-debounce-function
if (timeout) { //check if the timer has been set
clearTimeout(timeout); //clear the timer
}
//set a timer
timeout = setTimeout(handlePS, 250);
});
function handlePS() {
if (document.body.clientWidth >= 960) {
//check if ps is assigned as an instance of the ParticleSlider
if (ps != undefined && typeof ps !== null) {
ps.init(); //refresh the particle slider since it exists
console.log('called init on ps');
} else {
if (window.location.search.indexOf('d=1') > -1) {
debugger;
}
//otherwise create a new instance of the particle slider
ps = new ParticleSlider({
width: 1400,
height: 600,
imgs: imgs
});
}
}
else {
//when the flat logo is displayed, get rid of the particle slider instance
// delete ps;
ps = null;
}
}
})();
</script>
It now works fine across all the main browsers - Chrome/Safari/Firefox. It still feels a bit clunky as it pushes the rest of the page down whilst it is re-sizing and it takes probably a few seconds more than I'd like - not sure if there's a timer option to speed the reanimation up? Otherwise, everything is working fine.

Using time delays in Javascript

I have a gif image that I want to stretch by making the height and/or width variable. However, I want the image stretching to be done at a speed I set, so it is progressive and visible as it occurs on the screen. The code below works, but it renders the image immediately as a complete image, with no stretching visible. So I thought: insert some kind of timer function to slow down the execution of the "stretching" code. I have tried setTimeout and setInterval (using 1/100 sec delays), but I have not been able to make either work. What am I doing wrong here guys?
$(window).load(function(){
setInterval(function(){
var i=1;
for (i;i<400;i++) {
$("#shape1").html('<img src="image.gif" width="'+i+'" height="40">');
}
},10);
});
The problems with your code are that
at each interval iteration, you repeat the whole for loop
you never stop the interval looping
You may fix your existing code like this :
var i=1;
function step() {
$("#shape1").html('<img src="image.gif" width="'+i+'" height="40">');
if (i++<400) setTimeout(step, 10);
}
step();
Instead of replacing the #shape1 content each time, you could also simply change the width :
var i=1;
var $img = $('<img src="image.gif" width=1 height="40">').appendTo('#shape1');
function step() {
$img.css('width', i);
if (i++<400) setTimeout(step, 10);
}
step();
Demonstration
But jQuery has a very convenient animate function just for this kind of things.
As Dystroy suggested. Use jQuery animate instead
setInterval(function(){
var i=1;
for (i;i<400;i++) {
$("#shape1").animate({
width : i
},10);
}
}, 10);
Here is a jsfiddle
CSS3 transitions are great if your browser supports it.
.resize {
width: 200px;
height: 50px;
transition: width 1s ease;
}
Just add the class to an element to make it stretch out.
img.className = "resize";
css demo

overflow: hidden; image scrollBy

I had an idea for like a bus window as a fixed frame, about 800px wide, with a parallax city with the content on billboards spaced out so when you scroll between them it allows the parallax to look like bus is moving. The content will be much bigger than the window like a sprite and I'll put forward and back buttons that will scrollBy (x amount, 0). I have a working parallax script and a rough cityscape of 3 layers that all work fine.
I have hit a wall. I am trying to clear a scrollBy animation after it scrolls 1000px. Then you click it again and it goes another 1000px. This is my function.
function scrollForward() {
window.scrollBy(5,0);
scrollLoop = setInterval('scrollForward()',10);
}
So far I can only clear it when it gets to 1000. I tried doing 1000 || 2000 ect but after the first one it goes really fast and won't clear.
Excelsior https://stackoverflow.com/users/66580/majid-fouladpour wrote a great piece of code for someone else with a different question. It wasn't quite right for what the other guy wanted but it is perfect for me.
function scrollForward() {
var scrolledSoFar = 0;
var scrollStep = 75;
var scrollEnd = 1000;
var timerID = setInterval(function() {
window.scrollBy(scrollStep, 0);
scrolledSoFar += scrollStep;
if( scrolledSoFar >= scrollEnd ) clearInterval(timerID);
}, 10);
}
function scrollBack() {
var scrolledSoFar = 0;
var scrollStep = -75;
var scrollEnd = -1000;
var timerID = setInterval(function() {
window.scrollBy(scrollStep, 0);
scrolledSoFar += scrollStep;
if( scrolledSoFar <= scrollEnd ) clearInterval(timerID);
}, 10);
}
Now for step two figuring out how to put this content animation behind a frame.
Not quite sure what your asking here. Perhaps you could provide more relevant code?
I do see a potential issue with your code. You call setInterval('scrollForward()', 10) which will cause scrollForward to be called every 10ms. However, each of those calls to scrollForward will create more intervals to scrollForward creating a sort of explosion of recursion. You probably want to use setTimeout or create your interval outside of this function.
Also, as an aside you can change your code to simply: setInterval(scrollForward, 10). Removing the quotes and the parens makes it a littler easier to read and manager. You can even put complex, lambda functions like:
setInterval(function() {
scrollForward();
// do something else
}, 10);
edit:
So if you know that scrollForward moves the item 10px, and you want it to stop after it moves the item 1000px, then you simply need to stop it has moved that much. I still don't know how your code is actually structured, but it might look something like the following:
(function() {
var moved_by = 0;
var interval = null;
var scrollForward = function() {
// move by 10px
moved_by += 10;
if (moved_by === 1000 && interval !== null) {
clearInterval(interval);
}
};
var interval = setInterval(scrollForward, 10);
})();
If you want to clear it after 1000 or 2000, you simply adjust the if statement accordingly. I hope that helps.

How to make an image appear after 10 minutes using javascript?

Im trying to make a script in which an image appears for the user after 10 minutes. Think of it as a timer. And once the timer reaches 0, an image appears. Im pretty new to javascript, so I really have no idea where to start. Does anyone know of a script which will do the job, or maybe point me in the right direction? Thanks.
This is how you should add your image to your HTML
<img id="myimage" src="" style="display:none" />
Here is your JavaScript:
<script type="text/javascript">
setTimeout(function(){
document.getElementById('myimage').style.display = 'block';
},600000);
</script>
You can test it here
HTML:
<img src="yourimage.jpg" id="yourImageId" style="display: none" />
JS:
setTimeout(function() { document.getElementById('yourImageId').display('block'); }, 10 * 60 * 1000);
with setTimeout you set the timer to trigger after 10 * 60 * 1000 ms ( = 10 minutes); It triggers the function and display's the hidden image. Fore tidyness put your css for hiding the image in a proper css file.
Can you repeat this for every image in a slideshow? I have tried your code to blackout for, say 500 ms, the transition between previous image and the next image to prevent their concatenation. Since the (random) images have a very different aspect ratio, I do not use (cross)fading here. Now, your code only works once, right at the start of the show, and then the images are concatenated again. My piece of code
#blackit { display: none; }
<body>
<script>
document.write('<img id="blackit" onload="resizeImage()" margin="0" border="0" alt="" src="" '+rimages[Math.floor(Math.random()*(rimages.length))]+'">')
var timeoutID = setTimeout(function() { document.getElementById('blackit').style.display ='block'; }, 500);
var paused = false;
document.onkeydown = function(evt) {
evt = evt || window.event;
if (evt.keyCode == 32) {
paused = !paused;
}
};
(function loop() {
var rantime = Math.round(Math.random() * 7000) + 1000;
timeoutID;
setTimeout(function() {
if (!paused) {
rotateImage();
}
loop();
}, rantime);
})();
Have a look at setTimeout. You can hide the image initially (with CSS display: none;) and after the timeout finished, show the image.
Example:
var timeout = setTimeout(function() {
document.getElementById('imageID').style.display = 'block';
}, 10000); // of course you have to set the right time
As you want to detect user inactivity, also have a look at Detecting idle time in JavaScript elegantly and others.
Look for setTimeOut method in javascript if you can use jQuery 1.4+ it has jQuery delay function.
You could use the setTimeout() function to achieve this. The function takes two parameters, a function to run and the time to delay. 10 minutes = 600 seconds which works out as 600,000 milliseconds, which is the timescale JS uses. So you could do something like this, if you were using jQuery of course:
setTimeout(function() {
$("#my-img").show();
},600000);
Or if not do it with regular JS using:
setTimeout(function() {
document.getElementById("my-img").style.display = "block";
}, 600000);
setTimeout(function(){
// do some stuff here, like add an image for example...
}, (60 * 10 * 1000))
// seconds * minutes * 1000

Animated PNG background with Javascript, but without loop?

I need help with an animated PNG in Javascript.
I found how to animate a PNG background with Javascript here on Stack Overflow. But my problem is that I only need the animation onmouseover and onmouseout. And the animation should play only once, not in a loop, so when the user moves the mouse over a div the the animation in the background should play once and stop at the last frame, but when the user goes off the div, a reverse animation should play once and stop at the last (first) frame. The script I found here is:
The style:
#anim {
width: 240px; height: 60px;
background-image: url(animleft.png);
background-repeat: no-repeat;
}
The HTML:
<div id="anim"></div>
Javascript:
var scrollUp = (function () {
var timerId; // stored timer in case you want to use clearInterval later
return function (height, times, element) {
var i = 0; // a simple counter
timerId = setInterval(function () {
if (i > times) // if the last frame is reached, set counter to zero
i = 0;
element.style.backgroundPosition = "0px -" + i * height + 'px'; //scroll up
i++;
}, 100); // every 100 milliseconds
};
})();
// start animation:
scrollUp(14, 42, document.getElementById('anim'))
I hope anyone can help me, Thank you
To stop the animation after the first set of frames you do want to change the if condition to not reset the counter to zero but instead to clear the interval and stop it from reoccuring.
To only let it play when you enter an element you can attach the animation function as an event listener and play the whole thing in reverse with another function that you plug into your onmouseout event.
Depending on your target browser and since your question is fairly vague I can recommend two alternatives to you:
Use jQuery animate (all browsers, include ref to jquery)
//Animate to x,y where x and y are final positions
$('#anim').mouseenter(function(e) {
$(this).animate({background-position: x + 'px ' + y + 'px'}, 4200);
})
//Do same for mouseleave
Use a css3 animation (using -webkit browser here)
<style>
#-webkit-keyframes resize {
100% {
height: 123px;
}
}
#anim:hover {
-webkit-animation-name: resize;
-webkit-animation-duration: 4s;
}
I would choose option 2 if you are doing mobile development or can choose only css3 capable browsers.

Categories