Josh C
Josh C

Reputation: 261

Same window.addEventListener For 2 html files

Hello Everyone I have this problem that is just bugging me and I cant get it figured out. I looked everywhere and couldnt find an answer.

I have 2 html files and 1 external javascript file....

This is the first html file

<!doctype html>

<head>
    <title>.....</title>
    <script src="externalJsFile"></script>
</head>

<body>
    <input type="button" value="button1" id="button1">
    </div>
</body>

<html>

here is my second html file that links to the same external javsascript file

<!doctype html>

<head>
    <title>.....</title>
    <script src="externalJsFile"></script>
</head>

<body>
    <input type="button" value="button2" id="button2">
    </div>
</body>
</html>

Here is my external javascript file

window.addEventListener("load", setFunctions, false);


function setFunctions() {
    var button1 = document.getElementById("button1");
    var button2 = document.getElementById("button2");

    button1.addEventListener("click", sayHello, false);
    button2.addEventListener("click", sayHello, false);
}


function sayHello() {
    alert("hello");
}

When I visit each html page to click the button to see the hello popup box it only works in one of the pages. In the javascript if i switch around the order of the event listeners on the buttons then the popup will only work on the other page now!! someone please help!! Do I need separate external javascript files for each html page when a window event listener is used???

Upvotes: 1

Views: 2034

Answers (1)

Quentin
Quentin

Reputation: 943163

In the first HTML page, button1 is a button and button2 is null.

button1.addEventListener("click", sayHello, false); binds the event handler, then button2.addEventListener("click", sayHello, false); errors. Since there is no more code in the function, this has no noticeable effect unless you are watching the JS console.

In the second HTML page, it is the other way around: button2 is a button and button1 is null.

button1.addEventListener("click", sayHello, false); errors, and it never reaches the next line.

Test to see if (button1) {} and if (button2) {} before binding … and look at your JavaScript error console when you have problems.

Upvotes: 2

Related Questions