NiLL
NiLL

Reputation: 13843

Click event didn't attach to button

I need to attach a click event on a button tag. I've tried addEventLister, but it still doesn't work.

widget.innerHTML = "<button id=\"w_btn\">do action</button>";

w_btn = document.getElementById("w_btn");

w_btn.addEventListener("click", 
    function() {
        alert("sdf");
    }
);

Upvotes: 0

Views: 103

Answers (2)

Tieson T.
Tieson T.

Reputation: 21191

Hmm. I made a jsFiddle for you, here: http://jsfiddle.net/5hnPP/1/. Using a "real" button works. You may be running into a DOM issue. Let you know if I find anything more useful.

EDIT: Hmm, even adding the button dynamically works for me. Are you naming your element correctly? (Notice the updated jsFiddle link - has updated markup).

Upvotes: 1

Rob W
Rob W

Reputation: 348972

The third optional is required in some browsers.
The following code should work in every decent browser (fiddle: http://jsfiddle.net/5hnPP/2/):

var widget = document.getElementById("widget");
widget.innerHTML = "<button id=\"w_btn\">do action</button>";
var w_btn = document.getElementById("w_btn"); //Added var
w_btn.addEventListener("click",
    function() {alert("test")},
    false
);

Another possible cause is the existence of another element with ID w_btn, which appears before the #widget element. To solver this, you can adjust your code. Since you overwrite the contents of the #widget element, the first and only content is the button. Define:

var w_btn = widget.firstChild;

A last possibility is that you're in strict mode. In strict mode, using undeclared variables is forbidden.

Upvotes: 2

Related Questions