labilouser
labilouser

Reputation: 337

Play video on hover, play it on reverse on mouse off

The title of the post is pretty self-explanatory. I think I've managed to make it work, but unfortunately, it doesn't work exactly as it should. For example, when I hover the video and take the mouse off it in the first couple of seconds, the video won't start again on the second hover. If I keep my mouse on it for more than that, it will start on the second hover as well. Or it's not always playing on the hover etc.

What I'm missing? A little help would be appreciated. Thanks

var video = document.getElementById('video');
var intervalRewind;

$("#video").on("mouseover", function(event) {
    this.play();

  }).on('mouseout', function(event) {
   intervalRewind = setInterval(function(){
       video.playbackRate = 1.0;
       if(video.currentTime == 0){
           clearInterval(intervalRewind);
           video.pause();
       }
       else{
           video.currentTime += -.1;
       }
                },25);
});
video{
    height: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video id="video" muted>
    <source src="https://i.imgur.com/SWdBzDO.mp4" type="video/mp4">
</video>

Upvotes: 1

Views: 1268

Answers (2)

dbramwell
dbramwell

Reputation: 1326

Sometimes it seems to take a while for the video.currentTime to be 0, even if the video seems to have rewound back to the start, which means the interval isn't always cleared. Adding a clear interval in the mouseover seems to fix it. I've refactored a little too.

var video = document.getElementById('video');
var intervalRewind;

$("#video").on("mouseover", function(event) {
    clearInterval(intervalRewind);
    this.play();

  }).on('mouseout', function(event) {
   intervalRewind = setInterval(function(){
       video.pause();
       video.currentTime -= 0.1
       if(video.currentTime == 0){
           clearInterval(intervalRewind);
       }
   },25);
});
video{
    height: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video id="video" muted>
    <source src="https://i.imgur.com/SWdBzDO.mp4" type="video/mp4">
</video>

Upvotes: 3

Jax-p
Jax-p

Reputation: 8531

I think it's not possible in native way.

According to Web Audio playbackRate explained - mozilla.org:

Negative values will not cause the media to play in reverse.

Upvotes: 0

Related Questions