In this code, the onClick handler never gets called:
<html>
<head>
<title>Sample Web Page</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<form name=sampleform>
<div id="mainpage">
<img class="pageframe" src="images/Page 1.jpg" />
<input type="image" class="page2img" src="images/page2-link.jpg" onClick="DisplayPage2()"></input>
<input type="image" class="page3img" src="images/page3-link.jpg" onClick="DisplayPage3()"></input>
</div>
<script>
function DisplayPage2() {
document.getElementById("mainpage").innerHTML = "<img class="pageframe" src="images/Page 2.jpg" />";
}
function DisplayPage3() {
document.getElementById("mainpage").innerHTML = "<img class="pageframe" src="images/Page 3.jpg" />";
}
</script>
</form>
</body>
</html>
I can tell the images are getting clicked because the mouse coordinates are being displayed in the URL when I click on them, but the onClick handler is not being called. According to the documentation, onClick doesn’t work with input controls of type image. Given that, how do I get the image input controls to work?
2
Answers
The issue in your code stems from improper use of double quotes within your JavaScript strings, which leads to syntax errors.
You should either escape the inner double quotes or use single quotes for the strings within the
innerHTML
assignment.When using a form like this you must be careful that you are not submitting the form (and reload the page). Therefore, add
return false
after calling the function.When creating a function it is a good idea to generalize the function so that it can be used in more situations (like having more buttons…). The parameter for the function is "carried" by the element (the clicked button) as an attribute. Here, the value of the image button.
Instead of replacing the entire page (
document.getElementById("mainpage").innerHTML =
), just switch out thesrc
attribute of the image.