Notes

Play sound/video when image/link is clicked

Edit on GitHub

JavaScript

Demo

We need:

  • a js function for playing sound/video
  • a reference to that js function in the href tag of the image/link/video
  • an audio/video file with a unique id

JS

Basically, get the media file by id and use .play() to play it.

1  function play(media) {
2    document.getElementById(media).play();
3  }

HTML

The magic in using direct reference to js functions in the href tag. Like so: href="javascript:play('media')"

 1<!-- image --> 
 2<a href="javascript:play('dog')"><img src="img/dog.png"></img></a>
 3  
 4<!-- link -->
 5<a href="javascript:play('dog')">Dog</a>
 6  
 7<!-- audio file -->
 8<audio
 9    id="dog"
10    src="media/dog.wav"
11    preload="auto"
12></audio>