+ 1
Going Crazy!!! Need fresh eyes
i have tried to run the following code, give to me in a reputable book, to no avail. The script is supposed to allow the user to click on the button and change the background coloré I have spent a few hours going over the code by checking spelling, syntax, missing semi colon, comma, etc. could it be that perhaps the syntax is deprecated and i need to update the code to make it current var button=document.getElementById("button"); var rainbow=["red", "orange", "yellow", "green", "blue", "indigo", "violet"]; function change() { document.body.style.background = rainbow[Math.floor(7*Math.random())]; } button.addEventListener(click", change());
2 Answers
+ 1
Weâre going to finish the chapter with a second JavaScript program. This example
is much more complicated than the previous one and includes a lot of concepts
that will be covered in later chapters in more depth, so donât worry if you fail to
understand them at this stage! The idea is to show you what JavaScript is capable
of doing and introduce some of the important concepts that will be covered in the
upcoming chapters.
Weâll follow the practice of unobtrusive JavaScript mentioned earlier and keep our
JavaScript code in a separate file. Start by creating a folder called rainbow. Inside
that folder create a file called rainbow.htm and another folder called js that contains
a file inside it called scripts.js.
Letâs start with the HTML. Open up rainbow.htm and enter the following code:
rainbow.htm
<head>
<meta charset="utf-8">
<title>I Can Click A Rainbow</title>
</head>
<body>
<button id="button">click me</button>
<script src="js/scripts.js"></script>
</body>
</html>
This file is a fairly standard HTML5 page that contains a button with an ID of button.
The ID attribute is very useful for JavaScript to use as a hook to access different
elements of the page. At the bottom is a script tag that links to our JavaScript file
inside the js folder.
Now for the JavaScript. Open up scripts.js and enter the following code:
js/scripts.js
var button = document.getElementById("button");
var rainbow = ["red","orange","yellow","green","blue","indigo",
â„"violet"];
function change() {
document.body.style.background = rainbow[Math.floor(7*Math.
â„random())];
}
button.addEventListener("click", change);
+ 1
from the book on sitepoint Javascript from Novice to Ninja