I have a image on my html page and i want it to play a sound effect when i click on it. Here's the image code:
<img src="images/button1.png" width="32" height="32" onclick="alert();">
I want to change the alert box into the sound effect that i load in. How do i do it?
Well, it is not so easy, actually it is difficult to be accomplished ONLY with HTML. See here for more details.
You`ll face a various problems like:
Using A Hyperlink
If a web page includes a hyperlink to a media file, most browsers will use a "helper application" to play the file.
The following code fragment displays a link to an mp3 file. If a user clicks on the link, the browser will launch a helper application to play the file:
The best solution by my opinion is to use a Flash for playing sounds, i.e. make your links as Flash objects/buttons/text and assign sounds to them inside Adobe Flash on hover/click/etc.
Use SoundManager and will free up from a lot of headaches. Even more it will fallback nicely to flash if audio is not supported natively by browser.
However if you don't want to relay on a third party library there is another solution, a little bit daunting and exhausting but functional in every browser supporting the audio tag. The first thing you need to do is to populate the audio tag with the source content. You can do this with the following lines of code:
Because there is not a common agreement between different browser vendors regarding the supported audio format we need to include each supported ones. If one browser does not support it, then will skip it and fallback to the next one. If none of them is supported then you can use flash as a fallback. Google AJAX Libraries API will facilitate much our work. Below is the full source code:
Fiddle: http://jsfiddle.net/SMR4V/
Note: I have not created the ogg file, so won't work in firefox, because FF is using ogg files.