JavaScript changing image source not persisting
I have to change an image source when the image is clicked. The issue is the image changes only during the execution of the function, but revert to its initial value immediately after!!!
This is what I have done so far:
<head>
<title></title>
<script type="text/javascript">
function cardMouseClick(obj) {
el = document.getElementById(obj);
el.src = "image2.jpg";
alert("Hello!");
}
</script>
</head>
<body>
<form id="form1">
<input type="image" id="b1" src="image1.jpg"
onclick="cardMouseClick('b1')"/>
</form>
</body>
The image2 is duly displayed while the alert popup Windows awaits for user to click OK. Then it reverts to image1!
Why?
You have to prevent a page reload:
<form id="form1">
<input type="image" id="b1" src="image1.jpg"
onclick="cardMouseClick('b1'); return false;"/>
</form>
Because its submitting the form. return
false
from cardMouseClick(...)
.
You can do like this.
<head>
<title></title>
<script type="text/javascript">
function cardMouseClick(obj) {
el = document.getElementById(obj);
el.src = "image2.jpg";
alert("Hello!");
return false;
}
</script>
</head>
<body>
<form id="form1">
<input type="image" id="b1" src="image1.jpg"
onclick="cardMouseClick('b1')"/>
</form>
精彩评论