MrShabana
MrShabana

Reputation: 377

addEventListener has no effect when button clicked

HTML

<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html"; charset="utf-8" />
<script type="text/javascript" src="MouseEvent.js"></script>
<script type="text/javascript" ></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<button id="btn" type="button">Click Me!</button>
</body>
</html>  

Javascript

var handleclick = function(event)
{
document.body.style.bgColor="red";
};

var button = document.getElementById("btn");
button.addEventListener('click',handleclick,false);

For some reason when "btn" is clicked the background color does not change,what is going wrong here? thx

Upvotes: 1

Views: 481

Answers (1)

Quentin
Quentin

Reputation: 943564

Look in your JavaScript console. You will see that it is complaining that addEventListener is not a function because button is undefined.

Your script runs before the the button has been parsed into the DOM.

Move the script so it is after the button.

Alternatively, wrap the last two lines in a function and addEventListener('load', thatFunction).


Additionally, there is no bgColor property of style, you want backgroundColor.

Upvotes: 3

Related Questions