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);
}
Hi friends i want to fade in a div when i click on another div and for that i am using following code. Code1 works fine but i require to use the Code2.
I know there is jQuery but i require to do this in JavaScript
Can you guide me that what kind of mistake i am doing or what i need change...
Code1 --- Works Fine
function starter() { fin(); }
function fin()
{
for (i = 0; i <= 1; i += 0.01)
{
i=Math.round(i*100)/100;
setTimeout("seto(" + i + ")", i * 1000);
}
}
function seto(opa)
{
var ele = document.getElementById("div1");
ele.style.opacity = opa;
}
Code2 --- Does not work
function starter()
{
var ele = document.getElementById("div1");
fin(ele);
}
function fin(ele)
{
for (i = 0; i <= 1; i += 0.01)
{
i=Math.round(i*100)/100;
setTimeout("seto(" + ele + "," + i + ")", i * 1000);
}
}
function seto(ele,opa)
{
ele.style.opacity = opa;
}
Based on this site
EDIT-1
Added the functionality so that user can specify the animation duration(#Marzian comment)
You can try this:
function fadeIn(el, time) {
el.style.opacity = 0;
var last = +new Date();
var tick = function() {
el.style.opacity = +el.style.opacity + (new Date() - last) / time;
last = +new Date();
if (+el.style.opacity < 1) {
(window.requestAnimationFrame && requestAnimationFrame(tick)) || setTimeout(tick, 16);
}
};
tick();
}
var el = document.getElementById("div1");
fadeIn(el, 3000); //first argument is the element and second the animation duration in ms
DEMO
Update:
It seems that people enjoy my minimalistic and elegant approach, Updated for 2022:
No need for complex mechanisms. Just use CSS, which has it out of the box and has better performance overall.
Basically you achieve it with CSS by setting a transition for the opacity. In JavaScript that would be:
const div = document.querySelector('#my-div');
div.style.transition='opacity 1s';
and as a trigger you just set opacity to 0:
div.style.opacity=0;
This will create a 1 second fade out effect and you can use the trigger anywhere. The inverse can also be done to achieve a fade in effect.
Here's a working example:
const div = document.querySelector('#my-div');
div.style.transition='opacity 1s';
// set opacity to 0 -> fade out
setInterval(() => div.style.opacity=0, 1000);
// set opacity to 1 -> fade in
setInterval(() => div.style.opacity=1, 2000);
#my-div { background-color:#FF0000; width:100%; height:100%; padding: 10px; color: #FFF; }
<div id="my-div">Hello!</div>
Seems like your attempting to convert your element, to a string. Try this instead
function starter()
{
var ele = document.getElementById("div1");
fin(ele);
}
function fin(ele)
{
for (i = 0; i <= 1; i += 0.01)
{
i=Math.round(i*100)/100;
setTimeout(function() { setto(ele,i); }, i * 1000);
}
}
function seto(ele,opa)
{
ele.style.opacity = opa;
}
What happens here is, that i call a anonnymous function when the timer hits, and from that function, execute my functioncall to setto.
Hope it helps.
Jonas
The problem here is you are using the pass-a-string method of using setTimeout. Which is basically just a hidden eval.
It's worth noting that this is a bad practice, slow performer, and security risk.
(see questions such as this: setTimeout() with string or (anonymous) function reference? speedwise)
The reason this is causing your problem is because "seto(" + ele + "," + i + ")" is going to evaluate to "seto('[object HTMLDivElement]', 1)". You really want to pass reference to the ele object -- but the value's being cast to a string when you tried concatenating an object onto a string. You can get around this by using the pass-a-function method of using setTImeout.
setTimeout(function() { seto(ele, i); }, i * 1000);
I believe making this change will make your Code2 behavior equivalent to Code1.
Below are the complete answers to my question
ANS1 --- DEMO
function fin() {
var i = 0;
var el = document.getElementById("div1");
fadeIn(el,i);
}
function fadeIn(el,i) {
i = i + 0.01;
seto(el,i);
if (i<1){setTimeout(function(){fadeIn(el,i);}, 10);}
}
function seto(el,i) {
el.style.opacity = i;
}
ANS2 --- DEMO
function fin(){
var i = 0;
var el = document.getElementById("div1");
fadeIn(el,i);
}
function fadeIn(el,i) {
var go = function(i) {
setTimeout( function(){ seto(el,i); } , i * 1000);
};
for ( i = 0 ; i<=1 ; i = i + 0.01) go(i);
}
function seto(el,i)
{
el.style.opacity = i;
}
My version
function fadeIn($element){
$element.style.display="block";
$element.style.opacity=0;
recurseWithDelayUp($element,0,1);
}
function fadeOut($element){
$element.style.display="block";
$element.style.opacity=1;
recurseWithDelayDown($element,1,0);
}
function recurseWithDelayDown($element,startFrom,stopAt){
window.setTimeout(function(){
if(startFrom > stopAt ){
startFrom=startFrom - 0.1;
recurseWithDelayDown($element,startFrom,stopAt)
$element.style.opacity=startFrom;
}else{
$element.style.display="none"
}
},30);
}
function recurseWithDelayUp($element,startFrom,stopAt){
window.setTimeout(function(){
if(startFrom < stopAt ){
startFrom=startFrom + 0.1;
recurseWithDelayUp($element,startFrom,stopAt)
$element.style.opacity=startFrom;
}else{
$element.style.display="block"
}
},30);
}
function hide(fn){
var hideEle = document.getElementById('myElement');
hideEle.style.opacity = 1;
var fadeEffect = setInterval(function() {
if (hideEle.style.opacity < 0.1)
{
hideEle.style.display='none';
fn();
clearInterval(fadeEffect);
}
else
{
hideEle.style.opacity -= 0.1;
}
}, 20);
}
function show(){
var showEle = document.getElementById('myElement');
showEle.style.opacity = 0;
showEle.style.display='block';
var i = 0;
fadeIn(showEle,i);
function fadeIn(showEle,i) {
i = i + 0.05;
seto(showEle,i);
if (i<1){setTimeout(function(){fadeIn(showEle,i);}, 25);}
}
function seto(el,i)
{
el.style.opacity = i;
}
}
hide(show);
I just improved on laaposto's answer to include a callback.
I also added a fade_out function.
It could be made more efficient, but it works great for what i'm doing.
Look at laaposto's answer for implementation instructions.
You can replace the JS in his fiddle with mine and see the example.
Thanks laaposto!
This really helped out for my project that requires zero dependencies.
let el = document.getElementById( "div1" );
function fade_in( element, duration, callback = '' ) {
element.style.opacity = 0;
let last = +new Date();
let tick = function() {
element.style.opacity = +element.style.opacity + ( new Date() - last ) / duration;
last = +new Date();
if ( +element.style.opacity < 1 )
( window.requestAnimationFrame && requestAnimationFrame( tick ) ) || setTimeout( tick, 16 );
else if ( callback !== '' )
callback();
};
tick();
}
function fade_out( element, duration, callback = '' ) {
element.style.opacity = 1;
let last = +new Date();
let tick = function() {
element.style.opacity = +element.style.opacity - ( new Date() - last ) / duration;
last = +new Date();
if ( +element.style.opacity > 0 )
( window.requestAnimationFrame && requestAnimationFrame( tick ) ) || setTimeout( tick, 16 );
else if ( callback !== '' )
callback();
};
tick();
}
fade_out( el, 3000, function(){ fade_in( el, 3000 ) } );
Cheers!
function imgMan(){
var frames = 6;
var img = document.getElementsByClassName('img-man')[0];
var frame = 1;
var animation = setInterval(function() {
if (frame == frames) {
clearInterval(animation); return;
}
img.style.background = 'url(images/img-man-'+ frame++ + '.png) no-repeat';
}, 140);
}
This will run the function after 140ms that is each image would be changed after 140ms. But I need to run the function immediately and after then changing image should be after 140ms.
How can I do that?
I'm having currently this:
after 140ms img-man-1 after 140ms img-man-2 after 140ms img-man-3 and like so
But I need this:
after 0ms img-man-1 after 140ms img-man-2 after 140ms img-man-3 and like so
Just store it in a variable, and evoke it manually
function imgMan(){
var frames = 6;
var img = document.getElementsByClassName('img-man')[0];
var frame = 1;
var func = function() {
if (frame == frames) { clearInterval(animation); return; }
img.style.background = 'url(images/img-man-'+ frame++ + '.png) no-repeat';
};
var animation = setInterval(func, 140);
setTimeout(func, 0);
}
I am working on a little javascript gallery that displays a number of differenty images, and fades in and out. Unfortunately I can't seem to get the fade in properly working.
Can anybody tell me how to fix this?
This is my code so far:
//This goes in the head of the html file:
<script type="text/javascript">
var imageCount = 4;
var image = new Array(imageCount);
image [1] = "slideshow/testimg1.jpg"
image [2] = "slideshow/testimg2.jpg"
image [3] = "slideshow/testimg1.jpg"
image [4] = "slideshow/testimg2.jpg"
</script>
//This goes in the body of the html file
<img width="760" height="260" name="slide">
<script type="text/javascript">
var step = 1;
document.images.slide.style.opacity = 1;
function NextImage()
{
//Change image
document.images.slide.src = image [step];
//Change step
if (step < imageCount)
step++;
else
step = 1;
FadeIn();
}
function FadeIn()
{
if (document.images.slide.style.opacity < 1)
{
//Increase opacity
document.images.slide.style.opacity += 0.05;
setTimeout("FadeIn()", 20);
}
else
{
//Set opacity to 1, fade out
document.images.slide.style.opacity = 1;
setTimeout("FadeOut()", 4000);
}
}
function FadeOut()
{
if (document.images.slide.style.opacity > 0.05)
{
//Reduce opacity
document.images.slide.style.opacity -= 0.05;
setTimeout("FadeOut()", 20);
}
else
{
//Set opacity to 0.5, change the image
document.images.slide.style.opacity = 0.05;
NextImage();
}
}
NextImage();
</script>
The idea is that is swithes between the NextImage, FadeIn and FadeOut functions.
I have everything working except for the fades, because it whenever I test it it goes like this:
Load image, fade out, load second image, freeze.
I hope someone can help me with this.
Thanks in advance.
~Luca.
EDIT:
This fixed it:
//Increase opacity
var x = parseFloat(document.images.slide.style.opacity) + 0.05;
document.images.slide.style.opacity = x;
setTimeout(FadeIn, 20);
Thanks!
Change:
setTimeout("FadeIn()", 20);
to
setTimeout(FadeIn, 20);
and see if that helps (and the other setTimeout functions as well).
EDIT/Addition:
The document.images.slide.style.opacity += 0.05; is not actually incrementing. Try the following modification:
//Increase opacity
var x = parseFloat(document.images.slide.style.opacity);
x += 0.05;
document.images.slide.style.opacity = x;
setTimeout(FadeIn, 20);
Here's a working fiddle.
Actually wat is happening is the event stack where the set time out function saves the events to be executed after a particular interval is getting overflown :)
fiddle
try{
var imageCount = 4;
var image = new Array(imageCount);
image [1] = "http://i.dailymail.co.uk/i/pix/2009/06/01/article-0-05144F3C000005DC-317_468x387.jpg";
image [2] = "http://images.theage.com.au/ftage/ffximage/kaka_narrowweb__300x323,2.jpg";
image [3] = "http://ricardokakaonline.com/wp-content/uploads/2011/10/istoe.com_.br-kaka.jpg";
image [4] = "http://farm2.static.flickr.com/1226/1366784050_d697d3cde3.jpg";
var step = 1;
document.images.slide.style.opacity = 1;
function NextImage()
{
//Change image
document.images.slide.src = image [step];
//Change step
if (step < imageCount)
step++;
else
step = 1;
FadeIn();
}
function FadeIn()
{
if (document.images.slide.style.opacity < 1)
{
//Increase opacity
document.images.slide.style.opacity += 0.05;
setTimeout(FadeIn(), 200);
}
else
{
//Set opacity to 1, fade out
document.images.slide.style.opacity = 1;
setTimeout(FadeOut(), 2000);
}
}
function FadeOut()
{
if (document.images.slide.style.opacity > 0.05)
{
//Reduce opacity
document.images.slide.style.opacity -= 0.05;
setTimeout(FadeOut(), 200);
}
else
{
//Set opacity to 0.5, change the image
document.images.slide.style.opacity = 0.05;
NextImage();
}
}
NextImage();
}catch(e){
alert(e)
}
try using jquery to give fade in fade out .. I just added a try catch block to see Why it is freezing.
Heres a link for fade in fade out using javascript fade in out
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);
});