I am trying to fade the volume of an mp3 in to 1 if the body has the class fp-viewing-0
How ever this isn't working and the volume doesn't change how can I fix this?
Code:
var audio0 = document.getElementById('audio-0');
audio0.volume = 0;
setInterval( function(){
if ($("body").hasClass("fp-viewing-0")) {
audio0.animate({volume: 1}, 1000);
}
else {
audio0.animate({volume: 0}, 1000);
}
}, 100);
HTML
<audio id="audio-0" src="1.mp3" autoplay="autoplay"></audio>
I've also tried:
$("#audio-0").prop("volume", 0);
setInterval( function(){
if ($("body").hasClass("fp-viewing-0")) {
$("#audio-0").animate({volume: 1}, 3000);
}
else {
$("#audio-0").animate({volume: 0}, 3000);
}
}, 100);
Kind Regards!
I have changed the jquery animate part to a fade made by hand. For that i created a fade time and steps count to manipulate the fade effect.
var audio0 = document.getElementById('audio-0');
audio0.volume = 0;
if ($("body").hasClass("fp-viewing-0")) {
audio0.volume = 1; //max volume
var fadeTime = 1500; //in milliseconds
var steps = 150; //increasing makes the fade smoother
var stepTime = fadeTime/steps;
var audioDecrement = audio0.volume/steps;
var timer = setInterval(function(){
audio0.volume -= audioDecrement; //fading out
if (audio0.volume <= 0.03){ //if its already inaudible stop it
audio0.volume = 0;
clearInterval(timer); //clearing the timer so that it doesn't keep getting called
}
}, stepTime);
}
Better would be to place all of this in a function that receives these values a fades accordingly so that it gets organized:
function fadeAudio(audio, fadeTime, steps){
audio.volume = 1; //max
steps = steps || 150; //turning steps into an optional parameter that defaults to 150
var stepTime = fadeTime/steps;
var audioDecrement = audio.volume/steps;
var timer = setInterval(function(){
audio.volume -= audioDecrement;
if (audio.volume <= 0.03){ //if its already inaudible stop it
audio.volume = 0;
clearInterval(timer);
}
}, stepTime);
}
Which would make your code a lot more compact and readable:
var audio0 = document.getElementById('audio-0');
audio0.volume = 0;
if ($("body").hasClass("fp-viewing-0")) {
fadeAudio(audio0, 1500);
}
Related
I want to create a screensaver in JavaScript but I don't know how can I set the time between the images,.
I have an Ajax call and I see if the time is, for example, 2s or 90s, but I don't know how to set that time between images, this is my code:
var cont = 0;
var time = 1000
setInterval(function() {
console.log(tiempo);
if(cont == imagenes.length){
return cont = 0;
}else{
var imagen = imagenes[cont].imagen;
$('#imgZona').attr('src', imagen);
var time = imagenes[cont].tiempoVisible;
finalTime = Number(time);
}
cont++;
}, Number(finalTime ));
but the time between images is always the same, 1000, how can I change it for the time that I receive in the Ajax call? Which is imagenes[cont].tiempoVisible
I cannot comment as I don't have enough reputation, but take a look at this fiddle
https://jsfiddle.net/kidino/4mbpR/
var mousetimeout;
var screensaver_active = false;
var idletime = 5;
function show_screensaver(){
$('#screensaver').fadeIn();
screensaver_active = true;
screensaver_animation();
}
function stop_screensaver(){
$('#screensaver').fadeOut();
screensaver_active = false;
}
function getRandomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
}
$(document).mousemove(function(){
clearTimeout(mousetimeout);
if (screensaver_active) {
stop_screensaver();
}
mousetimeout = setTimeout(function(){
show_screensaver();
}, 1000 * idletime); // 5 secs
});
function screensaver_animation(){
if (screensaver_active) {
$('#screensaver').animate(
{backgroundColor: getRandomColor()},
400,
screensaver_animation);
}
}
It will change background-color on idle mouse for 5 seconds, you can replace the code to change image, instead of background color.
Control set every timeout on each iteration.
var cont = 0;
var time = 1000
function next () {
console.log(tiempo);
if(cont == imagenes.length){
cont = 0;
}
var imagen = imagenes[cont].imagen;
$('#imgZona').attr('src', imagen);
cont++;
setTimeout(next, Number(imagenes[cont].tiempoVisible));
}
setTimeout(next, Number(initialTime));
Also I fixed a frindge condition.
Sample:
http://codepen.io/anon/pen/xgZMVd/
html file:
<div class="game-page">
</div>
css file:
.game-page {
width: 1024px;
height: 768px;
position: absolute;
background-color: grey;
}
.stick {
position: absolute;
left: 50%;
margin-left: -94px;
top: -60px;
width: 188px;
height: 50px;
background-color: black;
}
js file:
$(document).ready(function() {
init();
});
var CSS_CLASS = { STICK: "stick" },
changeSpeedTime = 1000, //in milliseconds
gameTime = 60, //in seconds
timer = 1, //in seconds
windowWidth = 1024,
windowHeight = 768,
stickTop = -60,
restStickTime = 0, //in milliseconds
initialStickInterval = 1000, //in milliseconds
stickInterval = null, //in milliseconds
initialStickDuration = 7, //in seconds
stickDuration = null, //in seconds
stickTweensArray = [],
changeSpeedInterval = null,
countdownTimerInterval = null,
generateSticksInterval = null,
generateSticksTimeout = null,
$gamePage = null;
function init() {
initVariables();
initGamePage();
}
function changingSpeedFunction(x){
var y = Math.pow(2, (x / 20));
return y;
}
function initVariables() {
$gamePage = $(".game-page");
stickDuration = initialStickDuration;
stickInterval = initialStickInterval;
}
function initGamePage() {
TweenMax.ticker.useRAF(false);
TweenMax.lagSmoothing(0);
initGamePageAnimation();
}
function initGamePageAnimation () {
generateSticks();
changeSpeedInterval = setInterval(function () {
changeSpeed();
}, changeSpeedTime);
countdownTimerInterval = setInterval(function () {
updateCountdown();
}, 1000);
}
function changeSpeed () {
var x = timer;
var y = changingSpeedFunction(x); //change speed function
stickDuration = initialStickDuration / y;
stickInterval = initialStickInterval / y;
changeCurrentSticksSpeed();
generateSticks();
}
function changeCurrentSticksSpeed () {
stickTweensArray.forEach(function(item, i, arr) {
var tween = item.tween;
var $stick = item.$stick;
var oldTime = tween._time;
var oldDuration = tween._duration;
var newDuration = stickDuration;
var oldPosition = stickTop;
var newPosition = $stick.position().top;
var oldStartTime = tween._startTime;
var distance = newPosition - oldPosition;
var oldSpeed = distance / oldTime;
var newSpeed = oldSpeed * oldDuration / newDuration;
var newTime = distance / newSpeed;
var currentTime = oldStartTime + oldTime;
var newStartTime = currentTime - newTime;
item.tween._duration = newDuration;
item.tween._startTime = newStartTime;
});
}
function generateSticks () {
if (restStickTime >= changeSpeedTime) {
restStickTime -= changeSpeedTime;
restStickTime = Math.abs(restStickTime);
} else {
generateSticksTimeout = setTimeout(function () {
generateSticksInterval = setInterval(function () {
generateStick();
restStickTime -= stickInterval;
if (restStickTime <= 0) {
clearInterval(generateSticksInterval);
restStickTime = Math.abs(restStickTime);
}
}, stickInterval);
generateStick();
restStickTime = changeSpeedTime - Math.abs(restStickTime) - stickInterval;
if (restStickTime <= 0) {
clearInterval(generateSticksInterval);
restStickTime = Math.abs(restStickTime);
}
}, restStickTime);
}
}
function generateStick () {
var $stick = $("<div class='" + CSS_CLASS.STICK + "'></div>").appendTo($gamePage);
animateStick($stick);
}
function animateStick ($stick) {
var translateYValue = windowHeight + -stickTop;
var tween = new TweenMax($stick, stickDuration, {
y: translateYValue, ease: Power0.easeNone, onComplete: function () {
$stick.remove();
stickTweensArray.shift();
}
});
stickTweensArray.push({tween:tween, $stick:$stick});
}
function updateCountdown () {
timer++;
if (timer >= gameTime) {
onGameEnd();
clearInterval(changeSpeedInterval);
clearInterval(countdownTimerInterval);
clearInterval(generateSticksInterval);
clearTimeout(generateSticksTimeout);
}
}
function onGameEnd () {
var $sticks = $gamePage.find(".stick");
TweenMax.killTweensOf($sticks);
}
So, as I researched, I have next situation:
TweenMax (as it uses requestAnimationFrame) freezes when tab is inactive.
setInterval keep going when tab is inactive (also it's delay may change when tab is inactive, depends on browser)
Is there any other javascript functionality that changes when tab is inactive?
Then I have 2 solutions:
Freeze whole game, when tab is inactive.
Keep going, when tab is inactive.
With first solution I have next problem: as TweenMax uses requestAnimationFrame, it works correct according to this solution (freezes animation), but how can I freeze intervals and timeouts when tab is inactive and then resume intervals and timeouts?
With second solution I can use TweenMax.lagSmoothing(0) and TweenMax.ticker.useRAF(false) for animation and it works, but anyway something goes wrong with intervals and/or timeouts. I expected that animation goes wrong because of change of interval delay to 1000+ ms when tab is inactive (according to http://stackoverflow...w-is-not-active), but I disabled acceleration and set delays to 2000ms and it didn't help.
Please help me with at least one solution. Better with both to have some variety.
Resolved problem with first solution: freeze whole game. Just used TweenMax.delayedCall() function instead of setTimeout and setInterval and whole animation synchronized pretty well.
i have time progress bar. i use this code.i need time runner inside blue box.
how can i fix it, means when the yellow bar move depends on time need a time
display box.
var timer = 0,
perc = 0,
timeTotal = 2500,
timeCount = 1,
cFlag;
function updateProgress(percentage) {
var x = (percentage/timeTotal)*100,
y = x.toFixed(3);
$('#pbar_innerdiv').css("width", x + "%");
$('#pbar_innertext').text(y + "%");
}
function animateUpdate() {
if(perc < timeTotal) {
perc++;
updateProgress(perc);
timer = setTimeout(animateUpdate, timeCount);
}
}
$(document).ready(function() {
$('#pbar_outerdiv').click(function() {
if (cFlag == undefined) {
clearTimeout(timer);
perc = 0;
cFlag = true;
animateUpdate();
}
else if (!cFlag) {
cFlag = true;
animateUpdate();
}
else {
clearTimeout(timer);
cFlag = false;
}
});
});
#pbar_outerdiv { cursor: pointer; }
You already have the actual time in the updateProgress() method, so its as simple as changing the line setting the percentage to this:
$('#pbar_innertext').text((percentage / 100).toFixed(2) + " s");
JSFiddle: https://jsfiddle.net/McNetic/hnfRe/395/
Edit: With different browser, I now see the next problem: The animation can take much longer than the advertised time of 2500 ms (because of the very high update frequency of 1000 frames per second). So you should do less animation frames and calculate the percentage base on actual time measuring, like this:
https://jsfiddle.net/McNetic/hnfRe/396/
Check this JSFiddle. You can adjust the CSS: colours, sizes, etc to your needs.
Basically I put the text outside the #pbar_innerdiv in a span box.
<div id="pbar_outerdiv">
<div id="pbar_innerdiv"></div>
<span id="pbar_innertext">Click!</span>
</div>
Edit
So I edited the script and I hope now it matches your needs: JSFiddle Link. This is the script I used:
var timer = 0,
perc = 0,
percIncreaser,
timeTotal = 2500, //Only change this value time according to your need
timeCount = 1,
secondsCount=0,
cFlag;
function updateProgress(percentage,time) {
//var x = (percentage/timeTotal)*100;
$('#pbar_innerdiv').css("width", percentage + "%");
$('#pbar_innertext').text(time/1000 + "s");
}
function animateUpdate() {
if(perc < timeTotal) {
perc+=percIncreaser;
secondsCount+=10;
updateProgress(perc,secondsCount);
if(perc>=100) clearTimeout(timer);
else timer = setTimeout(animateUpdate, timeCount);
}
}
$(document).ready(function() {
$('#pbar_outerdiv').click(function() {
percIncreaser = 100/timeTotal*10;
if (cFlag == undefined) {
clearTimeout(timer);
perc = 0;
cFlag = true;
animateUpdate();
}
else if (!cFlag) {
cFlag = true;
animateUpdate();
}
else {
clearTimeout(timer);
cFlag = false;
}
});
});
I'm trying to make a 30 second countdown on a span element (#thirty) that will be started on click of another element (#start). It doesn't seem to work. I would appreciate your help.
var countdown = function() {
setTimeout(function() {
var i = 30;
do {
$("#thirty").text(i);
i--;
} while (i > 0);
}, 1000);
}
$("#start-timer").click(countdown());
use this :
var i = 30;
var countdown = function() {
var timeout_ = setInterval(function() {
$("#thirty").text(i);
i--;
if(i==0){
i = 30;
clearInterval(timeout_);
}
}, 1000);
}
$("#start-timer").click(countdown);
I'm developing an HTML5 application and I'm drawing a sequence of images on the canvas with a certain speed and a certain timeout between every animation.
Able to use it multiple times I've made a function for it.
var imgNumber = 0;
var lastImgNumber = 0;
var animationDone = true;
function startUpAnimation(context, imageArray, x, y, timeOut, refreshFreq) {
if (lastImgNumber == 0) lastImgNumber = imageArray.length-1;
if (animationDone) {
animationDone = false;
setTimeout(playAnimationSequence, timeOut, refreshFreq);
}
context.drawImage(imageArray[imgNumber], x, y);
}
function playAnimationSequence(interval) {
var timer = setInterval(function () {
if (imgNumber >= lastImgNumber) {
imgNumber = 0;
clearInterval(timer);
animationDone = true;
} else imgNumber++;
}, interval);
}
Now in my main code, every time startUpAnimation with the right parameters it works just fine. But when I want to draw multiple animations on the screen at the same time with each of them at a different interval and speed it doesnt work!
startUpAnimation(context, world.mushrooms, canvas.width / 3, canvas.height - (canvas.height / 5.3), 5000, 300);
startUpAnimation(context, world.clouds, 100, 200, 3000, 100);
It now displays both animations at the right location but they animate both at the interval and timeout of the first one called, so in my case 5000 timeout and 300 interval.
How do I fix this so that they all play independently? I think I need to make it a class or something but I have no idea how to fix this. In some cases I even need to display maybe 5 animations at the same time with this function.
Any help would be appreciated!
try something like this
var Class = function () {
this.imgNumber = 0;
this.lastImgNumber = 0;
this.animationDone = true;
}
Class.prototype.startUpAnimation = function(context, imageArray, x, y, timeOut, refreshFreq) {
// if (lastImgNumber == 0) lastImgNumber = imageArray.length-1;
if (this.animationDone) {
this.animationDone = false;
setTimeout(this.playAnimationSequence, timeOut, refreshFreq, this);
}
// context.drawImage(imageArray[imgNumber], x, y);
};
Class.prototype.playAnimationSequence = function (interval, object) {
var that = object; // to avoid flobal this in below function
var timer = setInterval(function () {
if (that.imgNumber >= that.lastImgNumber) {
that.imgNumber = 0;
clearInterval(timer);
that.animationDone = true;
console.log("xxx"+interval);
} else that.imgNumber++;
}, interval);
};
var d = new Class();
var d1 = new Class();
d.startUpAnimation(null, [], 300, 300, 5000, 50);
d1.startUpAnimation(null,[], 100, 200, 3000, 60);
It should work,
As far as I can see, each call to startUpAnimation will draw immediately to the canvas because this execution (your drawImage(..) call) hasn't been included in the callback of the setTimeout or setInterval.