codeandcloud
codeandcloud

Reputation: 55210

How to make poster behave like a hyperlink in html video

I have this audio mp3 which I wanna play in browser. The mp3 has an accompanying image and a url to navigate to when I click. So I put the mp3 in a video tag and made the image a poster like this

//cache the poster
var img = document.createElement("img");
img.src = "http://lorempixel.com/300/200";
// to make sure the poster is loaded before the video player appears
img.addEventListener("load", function(){
	var video = document.getElementById("demo-player");
  video.style.display = 'block';
	console.log("loaded!");
});
delete img;
<video id="demo-player" controls="controls" style="display: none;"
    src="http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2003.mp3"
    poster="http://lorempixel.com/300/200">
</video>

Now I want to make the poster clickable which I intend to do by creating a click event listener on the video tag. My questions are

  1. Is it correct to override the video's click event to make poster clickable? ( Are there any alternate methods?)
  2. Is there a way I can bring in cursor: pointer to the poster?

P.S: I am using the video tag here because, my audio will be an ad/announcement with an image and a link to navigate(if interested). And after this 4-5 second pre-roll audio, there will be a lengthy content video.

Upvotes: 1

Views: 723

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115222

Apply css cursor: pointer property for the video tag. For handling click event attach a click event handler. I don't think anything is wrong with using click event handler on video tag which doesn't effect the video controllers.

//cache the poster
var img = document.createElement("img");
img.src = "http://lorempixel.com/300/200";
// to make sure the poster is loaded before the video player appears
img.addEventListener("load", function() {
  var video = document.getElementById("demo-player");
  video.style.display = 'block';
  console.log("loaded!");
  video.addEventListener('click', function() {
    console.log('clicked');
  });
});
delete img;
video {
  cursor: pointer;
}
<video id="demo-player" controls="controls" style="display: none;" src="http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2003.mp3" poster="http://lorempixel.com/300/200">
</video>

Upvotes: 1

Related Questions