changing the background color from the external js.js
I want to create a basic script where someone clicks the button and the document color is changing. while I can do it with inline even handlers and also using the script block in html document, i am not able to achieve the result using the external js.js. My goal is not to use any even handlers at all inside the html document. This is how my codes looks like:
<head>
<title> Basics Exercise</title>
<script type="text/javascript" src="js.js"></script>
</head>
<body>
<form>
<p> Click this button and the document's color will change again </p>
<input name="button" type="button" value="Change the background color of the document"/>
</form>
js.js has
function changecolor() {
document.bgColor='#ea0d17';
}
document.forms[0].button.onClick=changecolor();
I don't want anyone to write a script for me, but I would appreciate if someone told me why the script I wrote is not working.
I don't use the xhtml standard much myself, but I recall someone on this site mentioning that using the name attribute in xhtml has been deprecated, so perhaps if you referenced your targets by ID instead of name that would work?
Thank very much for your responses. js is not an easy language to learn. Please help. My code still not working.
Devnull69-I changed the code as per your advice. but when I click the button -nothing happens.
DanInMa-referencing the button by Id -did not produce any result either.
the code looks like this:
<!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>
<title> Basics Exercise</title>
<script type="text/javascript" src="js.js"></script>
</head>
<body>
<form>
<input name="button" type="button" value="Change the background color of the document"/>
</form>
</body>
</html>
js file
function changecolor() {
document.bgColor='#ea0d17';
}
Yes, because it doesn't exist yet. HTML will be processed top-down (including Javascript) and Javascript will immediately be executed. By that time the form doesn't exist yet, because its HTML code has not yet been processed.