NewWebDesigner
asked on
Why isn't my onclick event working?
Why isn't my code working?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
body.onload = initPage;
function initPage() {
document.getElementById("input1").onclick= insertPicture;
}
function insertPicture() {
window.alert("hey");
}
</script>
</head>
<body>
<input type="text" id="input1" />
</body>
</html>
ASKER
Thanks that work great, but when I tried to export the javascript to a separate file, it stopped working.
Here is the html page: jstest.html
here is the javascript page:
buybooks.js
Here is the html page: jstest.html
here is the javascript page:
buybooks.js
Remember to edit the <body> tag to:
<body onload="initPage();">
and also to comment out the "//body.onload" in the buybooks.js file
I have updated both files as per attached.
updated-buybooks.js
jstest.html
<body onload="initPage();">
and also to comment out the "//body.onload" in the buybooks.js file
I have updated both files as per attached.
updated-buybooks.js
jstest.html
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
>>Why isn't my code working?
on your original code, on line 7 you are referring to an element that does not exist yet (body - which comes into existence at line 22). However, what DOES exist from the very beginning is window. So what you needed to do on your ORIGINAL code is to replace:
body.onload = initPage;
with:
window.onload = initPage;
If you use this approach you do NOT have to use <body onload="initPage()">
on your original code, on line 7 you are referring to an element that does not exist yet (body - which comes into existence at line 22). However, what DOES exist from the very beginning is window. So what you needed to do on your ORIGINAL code is to replace:
body.onload = initPage;
with:
window.onload = initPage;
If you use this approach you do NOT have to use <body onload="initPage()">
thus JS referenced a non existent <input> object
Solution was to place onload action in <body> tag as below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
//window.onload =initPage();
function initPage() {
document.getElementById('i
}
function insertPicture() {
window.alert("hey");
}
</script>
</head>
<body onload="initPage();">
<input id="input1" type="text"></input>
</body>
</html>