trouble with JavaScript innerHTML to image replacement

I am new to JavaScript and am doing a project for a class. I want to create an Easter egg somewhere on the page that when clicked changes the whole page code to a single image. This is my code just to test out the concept:

<div id = "all">
    <p>The button below changes the whole page.</p>

    <button type = "button" onclick = "changePage()">Click Here</button>
</div>

<script>
    function changePage()
    {
        document.getElementById("all").innerHTML = "<img src = "stop.jpg" />";
    }
</script>

The content isn't replaced by the image stop.jpg, however when I change the line to:

document.getElementById("all").innerHTML = "<h1>Whatever</h1>";

The code changes to the simple heading with no problems. Any idea why?

Upvotes: 0

Views: 216

Answers (2)

Barmar
Barmar

Reputation: 780663

The problem is with your quoting. The double quotes around the stop.jpg URL are ending the string that begins with <img. You need to use single quotes or escape the quotes:

document.getElementById("all").innerHTML = "<img src = 'stop.jpg' />";

document.getElementById("all").innerHTML = "<img src = \"stop.jpg\" />";

Didn't you get a syntax error in the Javascript console? Or notice the changed color in SO's syntax highlighting?

Upvotes: 0

nicael
nicael

Reputation: 18997

Didn't you notice that quotes are repeating? You should wrap your img with another quotes:

'<img src = "stop.jpg" />'

Or escape them

"<img src = \"stop.jpg\" />"

Upvotes: 1

Related Questions