Yuma Yanagisawa
Yuma Yanagisawa

Reputation: 235

The currentTime property not working in Chrome

I want to show a specific frame of a video by scrolling like this website(Apple Macbook). Setting the currentTime property seems to work in Firefox and Safari, however, it does not work in Chrome. I think the event type "loadedmetadata" is wrong for Chrome to add the event listener. The code is below.

HTML & JS

(function(document) {
  var video;
  $(function() {
    init();
  });

  function init() {
    video = document.getElementById('myVideo');
    video.addEventListener('loadedmetadata', function() {
      setClick();
      setScroll();
    });
  }

  function setClick() {
    $('#myButton').on('click', function() {
      video.currentTime = 2;
    });
  }

  function setScroll() {
    $(window).on('scroll', setFrame);
  }

  function setFrame() {
    var pos = $(window).scrollTop();
    console.log(pos);
    video.currentTime = pos/5;
  }

})(document);
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>funny thing</title>
  <link rel="stylesheet" href="main.css">
  <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
  <script src="main.js"></script>
</head>
<body>
  <button id="myButton">i am button</button>
  <video id="myVideo" controls height="800" preload="metadata">
    <source src="test.mp4" type='video/mp4; codecs="avc1.4D401E, mp4a.40.2"'>
  </video>

</body>
</html>

Upvotes: 0

Views: 2362

Answers (1)

undefined
undefined

Reputation: 4135

Works fine for me on Chrome if you just give it a valid url, your snippet won't work because test.mp4 does not exist. Here is a jsfiddle and a snippet:

(function(document) {
  var video;
  $(function() {
    init();
  });

  function init() {
    video = document.getElementById('myVideo');
    video.addEventListener('loadedmetadata', function() {
      setClick();
      setScroll();
    });
  }

  function setClick() {
    $('#myButton').on('click', function() {
      video.currentTime = 2;
    });
  }

  function setScroll() {
    $(window).on('scroll', setFrame);
  }

  function setFrame() {
    var pos = $(window).scrollTop();
    console.log(pos);
    video.currentTime = pos/5;
  }

})(document);
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>funny thing</title>
  <link rel="stylesheet" href="main.css">
  <script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
  <script src="main.js"></script>
</head>
<body>
  <button id="myButton">i am button</button>
  <video id="myVideo" controls height="200" preload="metadata">
    <source src="http://techslides.com/demos/sample-videos/small.mp4" type='video/mp4; codecs="avc1.4D401E, mp4a.40.2"'>
  </video>

</body>
</html>

Upvotes: 1

Related Questions