MiguelC
MiguelC

Reputation: 308

Changing Images src with Event "onclick"

<!DOCTYPE html>
<html>
<body>

<img id = "imageOne" src = "circleRed.png" onclick = "changeColor()"/>

<script>
var image =  document.getElementById("imageOne");

function changeColor() {
if (image.src == "circleRed.png") {
    image.src = "circleBlue.png"; 
} else {
    image.src = "circleRed.png";
}
}
</script>
</body>
</html>

This whole program may seem to work but no. I'll just be able to change the color of my image once. After clicking for the second time, nothing happens. What I mean is that I can only change the color from Red to Blue. Could you please help me figure out why?

Upvotes: 4

Views: 28846

Answers (5)

dnxdx
dnxdx

Reputation: 1

function changeColor(image) {
    if (image.src.indexOf("circleRed.png")>-1) {
        image.src = "circleBlue.png"; 
    } else {
        image.src = "circleRed.png";
    }
}
<img id = "imageOne" src = "circleRed.png" onclick = "changeColor(this)"/>

Upvotes: 0

Hussein Hn
Hussein Hn

Reputation: 173

try this code. just make sure to use (img.src.match) .And script inside the body.

var img = document.getElementById("image1");
img.addEventListener("mouseover", function(){
      if(img.src.match("images/image1.jpg")){
           img.src ="images/image1_2.jpg";}
       else {
           img.src = "images/image1.jpg"
            }  
})

<img src="images/image1.jpg" id="image1" />

Upvotes: 0

Pramod Kumar
Pramod Kumar

Reputation: 36

Here is the solution:

<!DOCTYPE html>
<html>
    <body>

        <img id ="imageOne" src ="circleRed.png" onclick = "changeColor()"/>

        <script>
            var image =  document.getElementById("imageOne");

            function changeColor()
            {
                if (image.getAttribute('src') == "circleRed.png")
                {
                    image.src = "circleBlue.png";
                }
                else
                {
                    image.src = "circleRed.png";
                }
            }
        </script>
    </body>
</html>

Upvotes: 2

Ibrahim Khan
Ibrahim Khan

Reputation: 20750

image.src returns the physical path of image. So you can use indexOf to match image name. Following code snippet may help you.

function changeColor(image) {
    if (image.src.indexOf("circleRed.png")>-1) {
        image.src = "circleBlue.png"; 
    } else {
        image.src = "circleRed.png";
    }
}
<img id = "imageOne" src = "circleRed.png" onclick = "changeColor(this)"/>

Upvotes: 0

Akshey Bhat
Akshey Bhat

Reputation: 8545

var image = document.getElementById("imageOne"); 

Move this inside function before if statement

Upvotes: 0

Related Questions