38

I have an HTML5 video with a poster attribute. I would like to somehow set it up so that you can click on anywhere on the video element (the area of the poster image) and it will fire the play event and start the video? I feel like this is fairly standard practice, but I can not find a way to do this without flash. Any help would be much appreciated.

Andrew
  • 1,247
  • 6
  • 15
  • 22

8 Answers8

71

This is working for me Andrew.

In your html head add this small piece of js:

var video = document.getElementById('video');
video.addEventListener('click',function(){
    video.play();
},false);

Or, just add an onlick attribute directly to your html element:

<video src="your_video" width="250" height="50" poster="your_image" onclick="this.play();"/>
XML
  • 19,206
  • 9
  • 64
  • 65
emags
  • 721
  • 5
  • 6
  • 29
    If you want to be able to pause the video on click too, change `onclick="this.play();"` to `onclick="this.paused?this.play():this.pause();"`. Idea courtesy of http://stackoverflow.com/a/20434695/1410871 – Daniel Golden Jan 29 '15 at 17:35
  • 4
    Also: this doesn't work in the latest version of Firefox on Mac (Version 35) because Firefox's video player already plays and pauses when you click within the video, and adding this code screws up Firefox's implementation. See [this SO post](http://stackoverflow.com/a/9851769/1410871) for details on how to detect the Firefox browser and avoid doing anything. – Daniel Golden Jan 29 '15 at 22:53
  • 5
    I modified the embedded onclick action to detect for the FireFox browser and disable code if needed. `onclick="if (typeof InstallTrigger == 'undefined') (this.paused ? this.play() : this.pause());"` It works on Mac FF, Mac Safari and Mac Chrome. Have not tested on Windows yet. – Dan Berlyoung Nov 13 '15 at 19:58
  • 2
    Dan, with 'controls' added (on windows using Chrome) this latest version (onclick="if (typeof InstallTrigger == 'undefined') (this.paused ? this.play() : this.pause());") needs two clicks to stop... if I remove the 'controls' part it does work – patrick Aug 11 '17 at 08:13
  • 1
    adding `return false;` to prevent default behavior fixed the issue that @patrick mentioned.. However, with this solution note that double-clicking will not trigger full-screen playback – Alex Oct 12 '21 at 10:35
19

Posted this here too but this applies to this thread too.

I had countless issues doing this but finally came up with a solution that works.

Basically the code below is adding a click handler to the video but ignoring all the clicks on the lower part (0.82 is arbitrary but seems to work on all sizes).

$("video").click(function(e){

    // handle click if not Firefox (Firefox supports this feature natively)
    if (typeof InstallTrigger === 'undefined') {

        // get click position 
        var clickY = (e.pageY - $(this).offset().top);
        var height = parseFloat( $(this).height() );

        // avoids interference with controls
        if (clickY > 0.82*height) return;

        // toggles play / pause
        this.paused ? this.play() : this.pause();
    }
});
Community
  • 1
  • 1
ios-lizard
  • 834
  • 1
  • 12
  • 19
  • 1
    The last line is awesome. Thanks. I don't have any trouble just using that alone, at least in Chrome. For anyone interested in the API for *all* these methods and properties, see: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_HTML5_audio_and_video and https://developer.mozilla.org/en/docs/Web/API/HTMLMediaElement – XML Dec 17 '14 at 13:09
  • Thanks for this, I looked everyone this one finally worked! – tiadotdev Apr 19 '16 at 20:23
  • 1
    Thanks, this is great but it doesn't work on Firefox, as it has this behavior by default. Add this line to the beginning of the function: if (typeof InstallTrigger !== 'undefined') return; (Taken from http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser/9851769#9851769 ) – Maciej Krawczyk Jul 30 '16 at 17:06
  • excellent. It's working out-of-the-box. I love paused toggle. Well done. Thanks for sharing! –  Jul 12 '17 at 13:37
6

Using the poster attribute does not alter the behavior. It just shows that image while loading the video. Having the video to automatically start (if the browser implementation does not do that), then you have to do something like:

<video id="video" ...></video>

in javascript using jquery:

$('#video').click(function(){
   document.getElementById('video').play();
});

Hope it helps

tiagoboldt
  • 2,426
  • 1
  • 24
  • 30
  • I agree, I thought that would work, but it doesn't seem to work. Any other thoughts? – Andrew Mar 11 '11 at 22:01
  • Probably because this example is using jQuery, which you may not have included. You may not need it of course. Check out emags' answer above for a non-jQuery example. – Ian Devlin Apr 10 '12 at 07:34
  • 4
    In your example no need to put document.getElementById('video').play(), you can just put this.play(). – Valjas Apr 05 '13 at 00:13
  • replace with this.play(); – Alex Skrypnyk Oct 31 '14 at 04:27
  • @Valjas but he might want every video on the page to play. /s – DickieBoy Mar 23 '16 at 15:40
  • @DickieBoy that is always a possibility. But from a use case perspective, it is not likely. Remember that mobile, tablets and many other devices don't support multiple players playing back video at the same time. So I feel the concise code if offered in my comment has more chance applying in a wider variety of situations. – Valjas Mar 24 '16 at 02:11
4

Yes, that sounds like a regular feature the browser creators or html spec writers just "forgot".

I've written a couple solutions but none of them are truly cross browser or 100% solid. Including problems with clicking on the video controls has the unintended consequence of stopping the video. Instead I would recommend you use a proven solution such as VideoJS: http://videojs.com/

deepwell
  • 20,195
  • 10
  • 33
  • 39
  • 1
    yes my problem is also the video player controls. it's easy to bind event listeners for whenever the user clicks on the HTML5 video element to play/pause. But this also happens when you click to adjust audio or pan the video scrubber. would be great to see browsers support this feature in the future – Jake Sep 12 '12 at 21:31
1

I was doing this in react and es6. Here is a modern version I made after reading Daniel Golden's solution:

const Video = ({videoSources, poster}) => {
  return (
    <video
      controls
      poster={poster}
      onClick={({target: video}) => video.paused ? video.play() : video.pause()}
    >
      {_.map(videoSources, ({url, type}, i) =>
        <source key={i} src={url} type={type} />
      )}
    </video>
  )
}
0

Using get(0) also works

    var play = $('.playbutton');
    var video = $('#video');
    play.click(function(){
        video.get(0).play();
    })
Jry
  • 127
  • 5
0

You can do it without using jQuery or anything. Just plain old JavaScript:

  1. Create a variable to store the video element.
  2. Detect the event (you can use any button you like).
  3. I detected the left mouse button in my example.
  4. The final line will toggle play and pause.
var video = document.getElementById('yourVideoId');
    document.onmousedown = function(e) {
    if (event.button == 0){
        video.paused ? video.play() : video.pause();
    }
}
Toni
  • 1,555
  • 4
  • 15
  • 23
-3
<script type="text/javascript">
    function actualNextSibling(el) {    // needed to smooth out default firefox/IE behavior
        do { el = el.nextSibling } while (el && el.nodeType !== 1);
            return el;
    }
</script>
<div onclick="actualNextSibling(this).style.display='block'; this.style.display='none'">
    <img src="splash.jpg" alt="splash" style="cursor: pointer" />
</div>
<div style="display: none">
    <iframe width="440" height="248" src="//www.youtube.com/embed/9FOZEbEpyA8?rel=0&autoplay=1"frameborder="0" allowfullscreen></iframe>
</div>
bummi
  • 27,123
  • 14
  • 62
  • 101
mdf
  • 1