Des Des - 5 months ago 24
CSS Question

Is it possible to replace these single quotes with double quotes?

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 &quot;, but that would make the code significantly harder to read.

<img id="image" src="images/bird.jpg" onmouseover="PlaySound(&quot;mySound&quot;); this.src=&quot;images/bird_second_frame.jpg&quot;" onmouseout="StopSound(&quot;mySound&quot;); this.src=&quot;images/bird.jpg&quot;">

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" 

    var element = document.getElementById("image");
    element.addEventListener("onmouseover", play);
    element.addEventListener("onmouseover", stop);

    function play() {
        this.dataset.original = this.src;
        this.src = this.dataset.frame;

    function stop() {
        this.src = this.dataset.original;