If section has class than start playing video

2.4k Views Asked by At

Please help me to make video play automatically when at the moment of scrolling on #video-section will be appeared .visible class name․ And vice versa, when .visible class name will be removed from section, the video will be stoped. Thanks.

<section class="cd-section">
        some content
</section>
<section id="video-section" class="cd-section">
    <video>
        <source src="http://www.w3schools.com/tags/movie.mp4" type="video/mp4">
    </video>
</section>
<section class="cd-section">
        some content
</section>

JSFiddle is here https://jsfiddle.net/y896ec5x/

3

There are 3 best solutions below

1
On BEST ANSWER

What you're doing (based on the comments):

$("video").play();
// or
$("video").pause();

Is invalid, as jQuery doesn't have these functions natively.

Try using the $.get method, which returns a regular JavaScript DOM object of the element:

$("video").get(0).play();
// or
$("video").get(0).pause();

Then to detect this at scrolling (parallax site without scrollbar), wrap it in a wheel event to handle that:

$("html, body").bind("mousewheel", function(){
  if ($("#video-section").hasClass("visible")) {
    $("video").get(0).play()
  } else {
    $("video").get(0).pause();
  }
});
1
On

You need to check is visible class in video-section if it is play video otherwise stop it, and you need to check this on scroll event, I've added body to be scrollable, but if it is inside some other tag use it.

$("body").scroll(function() {
    if ($('#video-section').hasClass('visible')) {
       $("video").play();
    } else {
        $("video").pause();
    }
});
0
On

Using an algorithm to detect if the element is completely in view from Check if element is visible after scrolling, you can do

$(window).scroll(function() {
  if (isScrolledIntoView('#video')) {
    $('#video').get(0).play();
  } else {
    $('#video').get(0).pause();
  }
});

function isScrolledIntoView(elem) {
  var $elem = $(elem);
  var $window = $(window);

  var docViewTop = $window.scrollTop();
  var docViewBottom = docViewTop + $window.height();

  var elemTop = $elem.offset().top;
  var elemBottom = elemTop + $elem.height();

  return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
.cd-section {
  height: 100vh;
}

#video {
  height: 50vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<section class="cd-section">
  some content
</section>
<section id="video-section" class="cd-section">
  <video id="video">


    <source src="http://www.w3schools.com/tags/movie.mp4" type="video/mp4">
      <source src="http://www.w3schools.com/tags/movie.ogg" type="video/ogg">
        Your browser does not support the video tag.
  </video>
</section>
<section class="cd-section">
  some content
</section>