palmin
palmin

Reputation: 297

click event for for video tag except when control clicked

I have a element where I would like to toggle the default controls when clicking the element, but when the controls are shown using these controls shouldn't toggle control visibility.

I'm adding the handler as bubbling, hoping that the built-in controls would preventDefault such that my handler was never invoked but the event caller is always called at least on Safari.

var video = document.getElementById("video");
video.addEventListener('click', function(evt) {
   video.controls = !video.controls
}); 

Is there some other way to add the event handler or perhaps properties on the event I can use to differentiate clicks on the video controls vs. clicks other places in the video element?

Upvotes: 0

Views: 1408

Answers (1)

VC.One
VC.One

Reputation: 15881

"Is there some other way to add the event handler or perhaps properties on the event I can use to differentiate clicks on the video controls vs. clicks other places in the video element?"

No Apple devices here to test on Safari but, in Chrome the clicking of a UI button (like "Play" or "Fullscreen") does not count as a click on the <video> element itself.

You can differentiate by knowing that if the element (picture part, not buttons) is clicked then it returns as: [object HTMLVideoElement]

In your code you can test as:

vid.addEventListener('click', function(evt) {
    alert("click target is : " + evt.target);
    vid.controls = !vid.controls
}); 

As a quick side-note, you can see how there is also an opportunity to create one "master" click function, like document.addEventListener('click' ... where you check the evt.target or even the evt.target.id and use If/Else to control anything clicked on the page from just one function. Example:

if (evt.target.id == "myVid") { ...do_someThing(); }

Finally, see if the code below is doing what you want to actually achieve...
You can preview the code at this W3Schools page :

<html>
<body>

<h1>Video UI : click test</h1>

<video id="myVid" width="320" height="240" loop controls>
<source src="movie.mp4" type="video/mp4">
</video>

<script>

var isPlaying = false;
var vid = document.getElementById("myVid");

vid.addEventListener("click", onclick );

function onclick(evt)
{
    evt.preventDefault();

    if ( vid.paused == true) { isPlaying = false; }
    else{ isPlaying = true; }

    if( evt.target.nodeName == "VIDEO") { vid.controls = !vid.controls; }

    if ( isPlaying == true) { vid.play(); }
}

</script>

</body>
</html>

Upvotes: 1

Related Questions