I have a simple webpage with an image in a div on the homepage and would like to use javascript to change the image for an alternative image after the page has loaded (only once) using a slow fade, i am currently using an animated gif to do this but would prefer to use javascript.
I have limited javascript skills.
thanks
I'm assuming that you won't use jQuery so i've created simple js eample which fades out one image and fades in other after page is loaded. You can check the example here http://jsfiddle.net/rJzPV/7/
function fadeOut(elem, time, callbackFn) {
var startOpacity = elem.style.opacity || 1;
elem.style.opacity = startOpacity;
(function go() {
elem.style.opacity -= startOpacity / (time / 100);
// for IE
elem.style.filter = 'alpha(opacity=' + elem.style.opacity * 100 + ')';
if (elem.style.opacity > 0.11)
setTimeout(go, 100);
else {
elem.style.display = 'none';
if (callbackFn)
callbackFn();
}
})();
}
function fadeIn(elem, time) {
var startOpacity = 0.1;
elem.style.opacity = startOpacity;
elem.style.display = "";
(function go() {
elem.style.opacity -= -startOpacity / (time / 1000);
// for IE
elem.style.filter = 'alpha(opacity=' + elem.style.opacity * 100 + ')';
if (elem.style.opacity < 1)
setTimeout(go, 100);
})();
}
window.addEvent('load', function () {
function changePicture() {
var _myImg = document.getElementById("myImage");
_myImg.src = "http://www.google.com/logos/2012/klimt12-hp.jpg";
fadeIn(_myImg, 1000);
}
var _myImg = document.getElementById("myImage");
fadeOut(_myImg, 1000, changePicture);
});
Related
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.
I've searched so much but I can't figure it out how to configure my bars.
I plan to put 3 loading bars that execute automatically according time:
1st will start from 30 to 60 seconds
2nd from 300 to 1800 seconds
3rd from 1801 to 1860 seconds
My Code is this ( be aware that I don't know how to change this values, I tried but don't work properly... This is the help I need, the frame stuff )
var my1Bar = setTimeout(start1Bar, 30000);
var my2Bar = setTimeout(start2Bar, 300000);
var my3Bar = setTimeout(start3Bar, 1800000);
function start1Bar() {
var elem = document.getElementById("my1Bar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
function start2Bar() {
var elem = document.getElementById("my2Bar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
function start3Bar() {
var elem = document.getElementById("my3Bar");
var width = 10;
var id = setInterval(frame, 10);
function frame() {
if (width >= 100) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
}
}
}
Thank you all
startBar(3000,4000 ,"my1Bar");
startBar(4001,20000 ,"my2Bar");
startBar(20001,22000,"my3Bar");
function startBar(start_ms,end_ms,id){
return setTimeout(function(){
loadBar(start_ms,end_ms,id);
}, start_ms);
}
function loadBar(start_ms,end_ms,id){
var elem = document.getElementById(id);
var widthAtStart = 0;
var widthAtEnd = 100;
var timeDuration=end_ms-start_ms;
var remindWidth=widthAtEnd-widthAtStart;
var curWidth=widthAtStart;
var lastTime=Date.now();
var intervalId = setInterval(frame, 10);
function frame() {
var dt=Date.now()-lastTime;
lastTime=Date.now();
var w=remindWidth*dt/timeDuration;
if (curWidth >= widthAtEnd) {
clearInterval(intervalId);
elem.style.width = '100%';
} else {
curWidth+=w;
elem.style.width = curWidth + '%';
}
}
}
.bars>div{
position:relative;
width:100%;
height:22px;
padding:1px;
margin:2px;
background:#ccc;
}
.bars>div>div{
position:absolute;
height:20px;
width:0;
background:red
}
<div class="bars">
<div><div id="my1Bar"></div></div>
<div><div id="my2Bar"></div></div>
<div><div id="my3Bar"></div></div>
</div>
Here is a bit refactored version of your code. To run a progress bar you need to call startBar() function with the time you want it to start and end and the id of a progress bar element. For example, in the code below the first bar will start after 1 second and end after 6 seconds (running for 5 seconds in total).
I also used HTML5 progress element. It is much better than using divs as progress is semantic and you don't have to manipulate any css parameters, you just change it's value. Plus it has a bonus of looking native to the platform and browser it is rendered on. However, if you want to style it to look the same on all platforms, it can be a bit of a pain. Here is a styling guide for progress element
startBar(1, 6, "first");
startBar(3, 6, "second");
startBar(5, 8, "third");
function startBar(from, to, id) {
// Convert seconds to miliseconds
from *= 1000;
to *= 1000;
// Delay the start of the loop for 'from' seconds
setTimeout(function() {
var bar = document.getElementById(id);
var duration = to - from;
var start = Date.now();
// Start the loop
var loop = setInterval(function() {
var runningFor = Date.now() - start;
if (runningFor <= duration) {
bar.value = Math.ceil(runningFor / duration * 100);
} else {
bar.value = 100;
clearInterval(loop);
}
}, 10);
}, from);
}
progress {
width: 100%;
}
<progress id="first" value="0" max="100"></progress>
<progress id="second" value="0" max="100"></progress>
<progress id="third" value="0" max="100"></progress>
I am terrible at javascript, how do I get function 1 (fade) to call / trigger function 2 (continuity) on completion of the volume fade as set out in the first. I have found answers in JQuery how would I do this in pure JS.
Function 1:
function fade(){
"use strict";
var timepiece,
soundwaves = document.getElementsByTagName("video")[0];
if (soundwaves.volume > 0) {
soundwaves.volume -= 0.005;
timepiece = setTimeout(fade, 80);
}
}
Function 2:
<!-- Continuity: (Javascript) -->
function continuity(){
var elements = document.querySelectorAll("main")[0];
elements.style.transition = "opacity 3s linear 0s";
elements.style.opacity = 1.0;
var audiofade,
audio = document.getElementById("ambience");
if (audio.volume < 1.0) {
audio.volume += 0.005;
audiofade = setTimeout(sync, 80);
}
}
simply call second in the else block
function fade()
{
"use strict";
var timepiece,
soundwaves = document.getElementsByTagName("video")[0];
if (soundwaves.volume > 0)
{
soundwaves.volume -= 0.005;
timepiece = setTimeout(fade, 80);
}
else
{
continuity();
}
}
I am making little reaction game for fun as I am new to this, It's quite a big challenge, so, I ran into the problem, how do I make script to stop from running when the button is pressed, I've managed to start everything when the start is clicked, but can't stop it from running.
Maybe anyone have any ideas how to make this happen? Here's my code so far:
Here's my HTML:
<button id="start">Start</button>
<button id="stop">Stop</button>
<button id="reset">Reset</button>
<p>Your reaction time: <u><span id="timeTaken"></span></u></p>
<p>Your average reaction time: <u><span id="average"></span></u></p>
<p>Your best reaction time: <u><span id="best"></span></u></p>
<div id="shape"></div>
And here's my javascript:
var start = new Date().getTime();
function getRandomColor() { //generates random color
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
function makeShapeAppear() { //makes that shape appear on screen
var top = Math.random() * 400;
var left = Math.random() * 400;
var width = (Math.random() * 200) + 100;
if (Math.random() > 0.5) {
document.getElementById("shape").style.borderRadius = "50%"
} else {
document.getElementById("shape").style.borderRadius = "0";
}
document.getElementById("shape").style.backgroundColor = getRandomColor();
document.getElementById("shape").style.top = top + "px";
document.getElementById("shape").style.left = left + "px";
document.getElementById("shape").style.width = width + "px";
document.getElementById("shape").style.height = width + "px";
document.getElementById("shape").style.display = "block";
start = new Date().getTime();
}
function appearAfterDelay() { //makes that shape appear after some delay
setTimeout(makeShapeAppear, Math.random() * 3000);
}
document.getElementById("reset").onclick = function() { //reset button, so when you click it, everything resets
location.reload();
}
var totaltime = 0;
var totalgames = 0;
document.getElementById("start").onclick = function() { //start button, so when you click it, shapes start appearing and time's running
appearAfterDelay();
document.getElementById("shape").onclick = function() {
document.getElementById("shape").style.display = "none";
var end = new Date().getTime();
var timeTaken = (end - start) / 1000;
totaltime += timeTaken;
totalgames += 1;
var notroundaverage = (totaltime / totalgames);
var roundaverage = notroundaverage.toFixed(3);
document.getElementById("timeTaken").innerHTML = timeTaken + " s";
document.getElementById("average").innerHTML = roundaverage + " s";
appearAfterDelay();
}
}
JavaScript is event based, and you really shouldn't attempt to 'stop' it. From looking at your code I can see that what you really want to do is clear the timeout when your button is clicked. This can be achieved by placing this line:
var timeOutId;
at the top of your code, and changing
setTimeout(makeShapeAppear, Math.random() * 3000);
to
timeOutId = setTimeout(makeShapeAppear, Math.random() * 3000);
Then, simply add a button with a click event that clears the timeout, which can be achieved using this line: window.clearTimeout(timeOutId);
There is a line in my page I want to delay 2 seconds and fade it in. Is there a way to do it without jQuery?
The site is
http://theclockpage.com/
And the text is the little line under the clock, the text is obtained through javascript that's why I don't add it to the question.
Thanks
var textCont = document.getElementById('clock').nextSibling;
textCont.style.opacity = 0;
setTimeout(function() {
var opacity = 0,
animate = setInterval(function() {
opacity += 0.05;
if (opacity >= 1) {
clearInterval(animate);
}
textCont.style.opacity = opacity;
}, 10);
}, 2000);
jsFiddle.
var d = document.getElementById("box");
function fadeOut(fadeScaler, hertz) {
if (!this instanceof Element) return false;
hertz = (!hertz) ? 60 : hertz; // Approx 60 hertz refresh rate
var opacity = this.style.opacity
opacity = "0";
var t = setInterval(
function() {
opacity = parseInt(opacity) + fadeScaler + '';
if (parseInt(opacity) >= 1)
clearInterval(t);
},
Math.floor(1000 / hertz)); // 1000 miliseconds / hertz = refresh rate
};
fadeOut.apply(d, [.05]);
Id use this one, Alex's function will not work. Opacity is a string and cannot be +='d with an integer.