Domanda

I have a video embedded in a site, and when a user plays the video I have JS to expand the video to the width of the site (and then shrink it on pause).

The video is being played/paused using the built-in controls, but when the video plays while expanding, it just looks weird, hence my desire to prevent playing until after the expansion.

However, preventDefault(); doesn't seem to be working in this instance. Does anyone know a way of achieving this? Thanks.

Here is my JS -

$(document).ready(function(){

    var video = $('#intro-video');

    video.on('play', function(e){

        e.preventDefault();

        video.animate({
            height:     '506',
            width:      '900'
        }, 500);

    });

    video.on('pause', function(e){

        video.animate({
            height:     '200',
            width:      '356'
        }, 500);

    });

});

And here is the HTML source -

<video id="intro-video" controls="">
    <source type="video/mp4" src="http://www.somesite.com/video.mp4"></source>
    Sorry, your browser is old and doesn't support the HTML5 'video' tag. Sucks to be you...
</video>
È stato utile?

Soluzione

Because you're using the inbuilt player controls, the video will start when you press play, and I don't believe you can prevent the event at this point in javascript.

I would recommend looking into creating your own controls for the player. That way, you can listen for the click event on the play button, and control the playback for the video directly.

Otherwise, the only thing I can think of is what I've done here: JSFiddle

Basically, when the video starts to play, pause it. Do the animation, then play it once the animation's finished. I've created a variable so the pause animation doesn't get triggered when we manually pause it:

var video = $('#intro-video');
var enlarged = false;

video.on('play', function(e){
    if (!enlarged){
        video[0].pause();
        video.animate({
            height:     '506',
            width:      '900'
        }, 500, function() {
            enlarged = true;
            video[0].play();
        });
    }
});

video.on('pause', function(e){
    if (enlarged) {
        enlarged = false;
        video.animate({
            height:     '200',
            width:      '356'
        }, 500);
    }
});

Altri suggerimenti

Actually it's very simple:

let videoShouldNotPlay = true
video.onplay = function () {
    if (videoShouldNotPlay) {
      video.pause()
      video.currentTime = 0 // set to the current time needed
      alert("You can't play the video right now")
      return
    }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top