Alternate image tag with js

Hi everyone,
This is my first javascript code and it is not working for me !
I try to place an image at a div. What that image would be it depends on a parameter I send to a js function.
This is what my HTML page:

<!DOCTYPE html>
<!--to-forum.html-->
<html lang = "he">
<head>
	<title>js</title>
	<meta charset="utf-8" />
	
	<script>
		function ChangeImage(xx)
		{ 
			if(xx=='1')
			{
				return("../images/greensilver.gif");
			}
			if(xx=='2')
			{
				return("../images/greensilver1.gif");
			}
		}
	</script>
</head>

<body>
	<div id="logo"> 
		<img id="myImg" src="ChangeImage('1')" />
	</div>
</body>
</html>

When I run it, the picture doesn’t show up. Nothing shows up :-(.
Could anyone instruct me how to do it right ?
Thanks

Hi @deotpit, you cannot set the source as such: src="ChangeImage('1')"
You will have to do something as below, it should work but please note I have not tested it.
Cheers

<!DOCTYPE html>
<!--to-forum.html-->
<html lang = "he">
<head>
	<title>js</title>
	<meta charset="utf-8" />
	<script>
		function ChangeImage(xx) { 
			if (xx=='1') {
				return("../images/greensilver.gif");
			} else if(xx=='2') {
				return("../images/greensilver1.gif");
			}
		}
	</script>
</head>
<body>
	<div id="logo"> 
		<img id="myImg" src="" />
		<script>
			var image = document.getElementById("myImg");
			image.src = ChangeImage("1");
		</script>
	</div>
</body>
</html>
2 Likes

Thank you so much Andres !
It worked just fine !

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.