I'm having some trouble trying to replace the single quotes ('...') with double quotes("...") in the following piece of code:
<img id="image" src="images/bird.jpg" onmouseover="PlaySound('mySound'); this.src='images/bird_second_frame.jpg'"
onmouseout="StopSound('mySound'); this.src='images/bird.jpg'">
Whenever I attempt to replace the single quotes with doubles, the code breaks, and I can't seem to find a different solution. I've been told not to use single quotes at all - is this an exception?
Any help is appreciated.
You can't use a literal "
inside an HTML attribute value delimited by "
characters. It will terminate the attribute value prematurely.
You can include one as "
, but that would make the code significantly harder to read.
<img id="image" src="images/bird.jpg" onmouseover="PlaySound("mySound"); this.src="images/bird_second_frame.jpg"" onmouseout="StopSound("mySound"); this.src="images/bird.jpg"">
I've been told not to use single quotes at all - is this an exception?
No. You've just been given bad advice.
JavaScript and HTML don't distinguish between '
and "
except when determining which characters can appear between them without being escaped.
Using '
in your example is simply more readable.
A better approach would be to avoid inline JavaScript entirely though.
<img id="image"
src="images/bird.jpg"
data-sound="mySound"
data-frame="images/bird_second_frame.jpg">
<script>
var element = document.getElementById("image");
element.addEventListener("onmouseover", play);
element.addEventListener("onmouseover", stop);
function play() {
PlaySound(this.dataset.sound);
this.dataset.original = this.src;
this.src = this.dataset.frame;
}
function stop() {
StopSound(this.dataset.sound);
this.src = this.dataset.original;
}
</script>