user2684521
user2684521

Reputation: 380

Javascript img tag src switch function not working

I have a small app the uses 3 images as buttons, the images are different colors, above the image buttons there is a big pair of glasses, depending on what color button you press the color of the glasses will change to match the color of the button that was pressed. The problem is I am getting a "Cannot set src to null" error.

Here is a jsfiddle: http://jsfiddle.net/vAF8S/

Here is the function

//Functions that change the glasses image
function changeColor(a){
    var img = document.getElementById("imgG");
    img.src=a;
}

Upvotes: 0

Views: 1137

Answers (2)

Alex
Alex

Reputation: 457

you are getting this error because you have applied ID twice to the same element

use this HTML

<section id="banner" >
    <img class="glasses" id="imgG" src="images/orangeG.png"><br>
    <img class="wcolorButton" src="images/whiteT.png"  />
    <img class="bcolorButton" src="images/blueT.png" />
    <img class="ocolorButton" src="images/orangeT.png"  onClick="changeColor('images/whiteG.png')" />
</section>

Upvotes: 0

Subash Selvaraj
Subash Selvaraj

Reputation: 3385

you have two Id's for the tag. you should have only one ID. change your html.

<section id="banner" >

        <img id="imgG" src="images/orangeG.png"><br>
        <img id="wcolorButton" src="images/whiteT.png"  />
        <img id="bcolorButton" src="images/blueT.png" />
        <img id="ocolorButton" src="images/orangeT.png"  onClick="changeColor('images/whiteG.png')" />
    </section>

FIDDLE

Upvotes: 2

Related Questions