0

I have a problem with addEventListener. When I click on third div tag it doesn't change background color and alert is not working also.

Here is my html structure:

<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript"  src="myscript.js"></script>
</head>
<body>
  <p>Click the button to display an alert box:</p>
  <div>Robert</div>
  <div>Arthur</div>
  <div>Procedure(Third)</div>
  <div>Fourth</div>
  <button onclick="myfunc()">Try it</button>
</body>

Here is javascript file:

var Ar = ["red", "yellow", "green", "blue"]

function getRandomInt(min, max)
{
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function myfunc() {
    alert(getRandomInt(0,5));

}

function Group(handler) {
    var R = [];
    for (var I = 0, E = document.getElementsByTagName('div'), L = E.length; I < L; I++) {
        handler && handler.call(E[I]);
        if (!handler)
            R.push(E[I]);
     }
    return R;
 }

 //get third div tags and set a handler
 Group()[2].addEventListener("click", handler, false);

function handler() {
    alert("Test!"); 
    Group()[2].style.backgroundColor = Ar[getRandomInt(0,3)];   
 }
Robert
  • 351
  • 1
  • 5
  • 15

2 Answers2

3

You are trying to access the elements before they get loaded.

Include your script at the end of the page and it will work.

<!DOCTYPE html>
<html>
<head>

</head>
<body>
  <p>Click the button to display an alert box:</p>
  <div>Robert</div>
  <div>Arthur</div>
  <div>Procedure(Third)</div>
  <div>Fourth</div>
  <button onclick="myfunc()">Try it</button>
</body>
<script type="text/javascript"  src="myscript.js"></script>
Ice Box
  • 1,514
  • 1
  • 14
  • 25
  • 2
    @Robert Yes you can use onload, but the problem with that is that it will wait for all the resources like images to get loaded to emit onload event. A better option can be jquery's Document.ready. – Ice Box Mar 17 '16 at 07:24
3

Modify your code like this.

<body>
    <p>Click the button to display an alert box:</p>
    <div>Robert</div>
    <div>Arthur</div>
    <div>Procedure(Third)</div>
    <div>Fourth</div>
    <button onclick="myfunc()">Try it</button>
    <script type="text/javascript">
        Group()[2].addEventListener("click", handler, false);
    </script>
</body>
Lahiru Ashan
  • 602
  • 9
  • 16