Search code examples
javascripthtmlcsssetintervalfadein

Javascript div fade in not working using setInterval


I'm trying to make a div containing a number of pictures to fade in but its not working and I don't know why. I believe that the inverval is not even being called. The div's opacity is set to 0.0 This is the code:

var movies = getElementById("movies");

    var apparence = function(){
        if(movies.style.opacity < 1.0){
            movies.style.opacity = movies.style.opacity + 0.1;
        } else { clearInterval(timer);
        }

    }

    var timer = window.setInterval(apparence, 1000);

Thank you very much.


Solution

  • To set your movies var, you need to call:

    document.getElementById('movies');
    

    The way you are attempting to increment opacity didn't work, so I've updated your example.

    New Code:

    var movies = document.getElementById("movies");
    var opacity = 0.1;
    var apparence = function(){
        if(opacity <= 1.0) {
            movies.style.opacity =  opacity;
        } else { 
            clearInterval(timer);
        }
        opacity += 0.1;
    }
    
    var timer = window.setInterval(apparence, 1000);
    

    JS Fiddle:

    http://jsfiddle.net/onov6cq4/1/