Search code examples
javascriptwordpresshtmlvideo

Play video, then redirect to a new page


I have a WordPress site with a page containing a video; I'd like this video to play automatically when the page is visited, and once the video has finished playing, I'd like a redirect to happen to a different page on my site.

I've followed the instruction from this post: Redirect html5 video after play

But this doesn't seem to work for me and I can't figure out what I should do differently.

Here's the code currently on my page:

<script src="text/javascript">
function playVideo(){
    var video = document.getElementById('addiction-video');
    video.play();
    video.addEventListener('ended',function(){
    location.href = 'http://mywordpresssite.com/addiction-a-call-for-connection-acim/';
    });
}
</script>
<video id="addiction-video" autoplay="autoplay" controls="controls" width="600" height="300">
<source src="http://mywordpresssite.com/wp-content/uploads/2015/12/Addictions.mp4" type="video/mp4" />
</video>

Can anyone tell why it's not redirecting after the video has finished playing?

I have the above code directly in my WordPress page; I've tried placing the script below the html, and I've tried adding the script into my theme settings, but neither made it work.

Thank you!


Solution

  • Firstly change <script src="text/javascript"> to <script type="text/javascript"> since you are not importing an external script file. Read a bit about <script> tag.

    Secondly you don't need the playVideo() function. Rewrite your code accordingly:

    <script type="text/javascript">
    
        var video = document.getElementById('addiction-video');
    
        video.addEventListener('ended',function(){
            location.href = 'http://mywordpresssite.com/addiction-a-call-for-connection-acim/';
        });
    
    </script>
    <video id="addiction-video" autoplay="autoplay" controls="controls" width="600" height="300">
        <source src="http://mywordpresssite.com/wp-content/uploads/2015/12/Addictions.mp4" type="video/mp4" />
    </video>
    

    You don't need video.play();, since you have autoplay="autoplay" attribute in <video> tag. Read about it here and try it yourself here.

    Thirdly keep your browser console open while writing a js code.

    Good Luck!