'Playing a video when clicking on an element of an image

I want to know if it's possible to play a video when you click on an element of an image, and play another video if you click on another element of the same image ?

For instance, imagine a picture of a room :

  • if I click on the area where the TV set is, the image disappears and video1 starts.
  • if I click on the chair, same thing but video2 starts instead.

Is this possible using HTML5 and Javascript? If so, how am I going to do that ?



Solution 1:[1]

Yes, it is possible.

I'm assuming that you have basic understanding of HTML and JavaScript. Also this will only work on browsers that have support for HTML5 and the video element specifically.

First, add a video element to your page

<video id="video" width="600">
  <source type="video/mp4">
  Your browser does not support HTML5 video.
</video>

Then let's assume you have two images, Video 1 and Video 2

<img src="tv.png" id="video1Btn" onclick="loadVideo1()" value="Load Video 1" />
<img src="chair.png" id="video2Btn" onclick="loadVideo2()" value="Load Video 2" />

Once a button is clicked the JavaScript function as in the onclick attribute will be called.

function loadVideo1() {
 var videoEl = document.getElementsByTagName('video')[0];
 var sourceEl = videoEl.getElementsByTagName('source')[0];
 sourceEl.src = 'video1.mp4';
 videoEl.load();
}

function loadVideo2() {
 var videoEl = document.getElementsByTagName('video')[0];
 var sourceEl = videoEl.getElementsByTagName('source')[0];
 sourceEl.src = 'video2.mp4';
 videoEl.load();
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pseudoh