I am new to javascript and want to make sure I am on the right track when playing a sound. Is there anything I should not be doing better or not be doing at all. Below is a simple function.
<script language="javascript" type="text/javascript">
function playSound(soundfile) {
if (navigator.userAgent.indexOf('Firefox') != -1) {
document.getElementById("dummy").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" type=\"application/x-mplayer2\" />";
} else {
document.getElementById("dummy").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" />";
}
}
</script>
</head>
<body>
<span id="dummy"></span>
<a href="#" onclick="playSound('doorbell.wav');">Click here to hear a sound</a>
</body>
I am not sure whether I should be using the audio tag or not. I appreciate any feedback
3 Answers 3
Don't duplicate sections of code! In particular, avoid putting 'execution' code in these simple conditionals, instead use them to build a shared executor:
function playSound(soundfile) {
var type_attr = '';
if (navigator.userAgent.indexOf('Firefox') != -1) {
type_attr = "type=\"application/x-mplayer2\"";
}
document.getElementById("dummy").innerHTML = "<embed src=\"" + soundfile + "\" hidden=\"true\" autostart=\"true\" loop=\"false\" " + type_attr + " />";
}
Regarding the HTML:
script
element
For JavaScript, you can simply use <script>
without the type
attribute:
If the language is not that described by "text/javascript", then the
type
attribute must be present
The language
attribute is obsolete:
Authors should not specify a
language
attribute on ascript
element.
a
element
I'd say a real button should be used here, not a link:
button
element withbutton
type:<button type="button" onclick="...">Click here to hear a sound</button>
input
element withbutton
type:<input type="button" onclick="..." value="Click here to hear a sound" />
Use jQuery and then do it like this:
<pre>
<script>
$(document).ready(function() {
var obj = document.createElement("audio");
obj.setAttribute("src", "http://kahimyang.info/resources/click.m...
$.get();
$(".playSound").click(function() {
obj.play();
});
});
</script>
</pre>
Put this snippet at the bottom of the page after that all anchors with class "playSound" will play a sound. Somewhere in your page your link should look loke below:
<pre>
<a href="#" class="playSound">Play</a>
</pre>
For more details visit this blog:
embed
instead ofaudio
? \$\endgroup\$