jQuery Change video poster based on time of day

时间:2016-03-04 17:58:17

标签: jquery html5 video

I am trying to change the poster of my video based on time of day but it is not working and seems to do nothing and throws no errors.

<video width="100%" poster="/poster.jpg"  id="videoPlayer" controls>
<source src="1.ogv" type='video/ogg; codecs="theora, vorbis"'/>
<source src="1.webm" type="video/webm" >    
<source src="1.mp4" type="video/mp4">     
</video>

jQuery code

$( document ).ready(function() {
function posterImageTime() {
            var d = new Date();
            var n = d.getHours();
            switch(true) {
                case (n > 19) :
                    //Night
                    posterImage = 'night.jpg';
                    break;
                case (n > 16 && n < 19) :
                    //Sunset
                    posterImage = 'sunset.jpg';
                    break;
                default:
                    //Day
                    posterImage = 'day.jpg';
            }
            document.getElementById("#videoPlayer").poster = posterImage;
            //$('#videoPlayer').attr('poster' , posterImage)
        }

});

3 个答案:

答案 0 :(得分:1)

Its likely because you are only defining the function within document.ready. Try defining the function outside of ready, and calling that function inside of ready: DEMO

function posterImageTime() {
    var d = new Date();
    var n = d.getHours();
    switch(true) {
        case (n > 19) :
            //Night
            posterImage = 'night.jpg';
            break;
        case (n > 16 && n < 19) :
            //Sunset
            posterImage = 'sunset.jpg';
            break;
        default:
            //Day
            posterImage = 'day.jpg';
    }
    document.getElementById("#videoPlayer").poster = posterImage;
    //$('#videoPlayer').attr('poster' , posterImage)
}

$( document ).ready(function() {
    posterImageTime();
});

Side note:

Don't include the # in getElementById. document.getElementById("videoPlayer") will suffice.

Also its good form to declare your variables before assigning their values. You should declare posterImage like this: var posterImage = null; before your switch statement.

答案 1 :(得分:0)

You have to call the function somewhere: posterImageTime(). Now you are just saying. Hey, when you are ready load this function and just stay there without ever being called.

答案 2 :(得分:0)

Might be as simple as:

document.getElementById("#videoPlayer").poster = posterImage;

change to:

document.getElementById("videoPlayer").poster = posterImage;

You actually need to call the function also:

function posterImageTime();