user3002180
user3002180

Reputation: 431

AddEventListener for button dynamically

Code:1 gives me error Cannot call method 'addEventListener' of null, because button is templated after script code is executed.

Code:1

<html>
<script>
    var button = document.getElementById("buttonid");
         button.addEventListener("click", function() { console.log("alert");});
</script>
<body>
    <input type="button" id="buttonid" value="click">
</body>
</html>

Code:2

<html>
<body>
<input type="button" id="buttonid" value="click">
</body>
     <script>
        var button = document.getElementById("buttonid");
             button.addEventListener("click", function() { console.log("alert");});
     </script>
</html>

Here code:2 is working. I want Code:1 to be work as Code:2. How to solve this problem.

Note:

I don't want to use jQuery

Upvotes: 0

Views: 3425

Answers (3)

UweB
UweB

Reputation: 4110

The problem is that the HTML page is parsed "as is", meaning top-down, so the script executes before the button's HTML code has been processed by the browser. Thus, your call to getElementById will return null.

If you really insist on having your JavaScript at the top of the page, you will need attach your event handlers AFTER the DOM tree is fully loaded ("DOM ready"). Careful though, older browsers might not support that event (it only became standardized with HTML5, although older Mozilla browsers will already know it)

<head>
<script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function (ev) {
        var button = document.getElementById("buttonid");
        button.addEventListener("click", function () {
            console.log("alert");
        });
    }, true);
</script>
</head>

See JSFiddle: http://jsfiddle.net/G3YWJ/

Upvotes: 1

Quentin
Quentin

Reputation: 943193

Either:

  1. Put the code that binds the event listener in a function, then bind that function as a load event listener on the window or
  2. Bind the listener to another object (such as the document), capture the event object (the first argument), then check the value of evt.target inside the function.

Upvotes: 2

Danilo Valente
Danilo Valente

Reputation: 11342

The problem is that when you call .getElementById in code 2, the page's body content is not loaded yet and then your button doesn't exist. Try using an onload event:

<html>
<body>
<input type="button" id="buttonid" value="click">
</body>
     <script>
        window.addEventListener("load", function () {
            var button = document.getElementById("buttonid");
                 button.addEventListener("click", function() { console.log("alert");});
        });
     </script>
</html>

Upvotes: 1

Related Questions