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>
var image = document.getElementById("imageOne");
Move this inside function before if statement
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" />
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)"/>
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)"/>