Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set an HTML5 Video to PAUSE when video player is out of view

I'd like to do this with javascript. I'm building a presentation using Hakim El Hattab's Reveal.js as a foundation.

The way Reveal.js works is the current slide you are viewing has a class of .present, any previous slides have a class of .past, and any slides yet to come into view have a class of .future.

I would like it to automatically pause any video that is inside a slide set to .past or .future.

How should I go about this?

Thanks in advance!

************UPDATE**************

so thanks to some direction i got over on the css-tricks forums i was able to get it working on a single video using getElementById.

below is the javascript i'm using to add the .past and .future classes and simultaneously pause a video.

if( i < index ) {
    // Any element previous to index is given the 'past' class
    slide.setAttribute('class', 'past');
    document.getElementById('vid').pause();
}
else if( i > index ) {
    // Any element subsequent to index is given the 'future' class
    slide.setAttribute('class', 'future');
    document.getElementById('vid').pause();
}

the issue that i'm having now is how would i apply it to a tag name (ie: video) or possibly a class.

like image 457
dfogge Avatar asked Nov 18 '25 01:11

dfogge


1 Answers

Now that you posted your code, it makes it easier to fix:

if( i < index ) {
    // Any element previous to index is given the 'past' class
    slide.setAttribute('class', 'past');
    var vids = document.getElementsByClassName("past");
    for (var i = 0; i < vids.length; i++) {
        vids[i].pause();
    }
}
else if( i > index ) {
    // Any element subsequent to index is given the 'future' class
    slide.setAttribute('class', 'future');
    var vids = document.getElementsByClassName("future");
    for (var i = 0; i < vids.length; i++) {
        vids[i].pause();
    }
}

See if that helps. If it doesn't, are you using a modern and standards-compliant browser? getElementsByClassName() is a relatively new feature. It works in the latest version of Chrome for me.

like image 156
petschekr Avatar answered Nov 19 '25 17:11

petschekr