dungey_140
dungey_140

Reputation: 2802

jquery <video> .play not working on mobile

I have a number of HTML5 <video> elements on my page, and all is working well on desktop. However, on iOS Safari, the only plays upon a long hold on the video, rather than a normal tap (which should replicate the 'click' jquery function). Can anybody suggest why the video isn't playing upon tap? And why it does so after a short hold?

$(document).ready(function() {

  // Preload the video
  setTimeout(function() {
    $('.video video')[0].load();
  }, 0);

  $('.video video').click(function() {
    if ($(this).hasClass('is-playing')) {
      $(this).removeClass().addClass('is-paused');
      // Pause video
      $(this)[0].pause();
    } else {
      $(this).removeClass().addClass('is-playing');
      // Play video
      $(this)[0].play();
    }
    return false;
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video src="video-url" poster="poster-url" preload></video>

Upvotes: 1

Views: 3257

Answers (1)

Pedram
Pedram

Reputation: 16575

You need to use touchstart event with on function:

$(document).ready(function() {

  setTimeout(function() {
    $('.video video')[0].load();
  }, 0);

  $('.video video').on('click touchstart', function() {
    // Change is here -------^
    if ($(this).hasClass('is-playing')) {
      $(this).removeClass().addClass('is-paused');
      $(this)[0].pause();
    } else {
      $(this).removeClass().addClass('is-playing');
      $(this)[0].play();
    }
    return false;
  });

});

touchstart

Upvotes: 1

Related Questions