Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 onClick toggled by clicking controls

I added an event listener to my video element so that users can play or pause the video by clicking anywhere on the element. I noticed that the event fires even when I click on the video controls (such as changing the volume slider), which obviously was not my intention.

Is there a relatively simple workaround for this?

like image 832
David B Avatar asked Oct 04 '22 01:10

David B


1 Answers

You can handle the onclick event of the video element with a function that accepts an event argument. This event argument will be populated with a lot of data about the mouse click, including its X/Y position in the layer (which should be the video tag)

From there you can trigger your play/pause event only when the click is in certain areas of the video. I've included an example below where we handle clicks everywhere in the video except the bottom 50 pixels.

document.getElementById("videoElement").onclick = function(ev){
    var vid = document.getElementById("videoElement");
    var heightOfControls = 50; 
// You'll have to figure out a good height to use for your unclickable region where the controls are.
// I used 50 pixels as an example.
    var areaAboveControls = vid.height - heightOfControls;

// the layerY attribute of the event lets us know where the mouse was within the topmost layer when the click occurred.
// Using this we can find out where we are in the video and react accordingly.
// Remember that 0 is at the top of the screen on the Y axis, so we need to use greater than to find out if it's BELOW
// our area above the controls.
    if(ev.layerY > areaAboveControls)
    {
        alert("Clicked controls!");
    }
    else
    {
        alert("Did not click controls");
        // Raise play/pause event from here since the controls won't handle the event and we can safely toggle play/pause.
    }
};

With a little bit of experimentation you should be able to find a nice value for heightOfControls that gives you the behavior you're looking for.

Fiddle: http://jsfiddle.net/hTYck/4/

Hope this helps!

like image 112
JessieArr Avatar answered Oct 13 '22 12:10

JessieArr