jqueryvideo

Show pause/play icons when hover/mouseenter over video


So this code works as expected. Hover/mouseenter/mouseleave shows and displays the pause/play icons correctly.

The issue I have is on page load the pause icon doesn't show on Hover/mouseenter? It only works after first click... Any help appreciated, thank you.

// HTML
<div class="video-container">
  <div class="video-controls"> </div>
  <video autoplay muted loop id="myVideo">
  <source src="img/video.mp4" type="video/mp4" />
  </video>
</div>
// END HTML

// jQuery
// Show video Play/Pause icons
$("#myVideo").mouseenter(function() {
    $('.video-controls').show();
}).mouseleave(function() {
    $('.video-controls').hide();
});


// Pause/Play video on hover
$("#myVideo").bind("click", function () {
  var vid = $(this).get(0);
      if (vid.paused) {
        vid.play();
        $('.video-controls').html('<i class="fas fa-pause-circle pause"></i>');
      } else {
        vid.pause();
        $('.video-controls').html('<i class="fas fa-play-circle play"></i>');
      }
  });

Solution

  • // HTML
    <div class="video-container">
      <div class="video-controls"><i class="fas fa-pause-circle play"></i></div>
      <video autoplay muted loop id="myVideo">
      <source src="img/video.mp4" type="video/mp4" />
      </video>
    </div>
    // END HTML
    
    // jQuery
    // Show video Play/Pause icons
    $("#myVideo").mouseenter(function() {
        $('.video-controls').show();
    }).mouseleave(function() {
        $('.video-controls').hide();
    });
    
    
    // Pause/Play video on hover
    $("#myVideo").bind("click", function () {
      var vid = $(this).get(0);
          if (vid.paused) {
            vid.play();
            $('.video-controls').html('<i class="fas fa-pause-circle pause"></i>');
          } else {
            vid.pause();
            $('.video-controls').html('<i class="fas fa-play-circle play"></i>');
          }
      });
    

    I found that after click event you have binded html so we need default state so just put default video control to play icon.