I'm creating objects in JavaScript that contain html, which are basically buttons that contain dynamically created words and do functions that use those words. I need to be able to attach onclick event handlers on them either when they're created or afterwards.
var MyClass = function(word) {
this.word = word;
this.wordHtml = '<span class="option">' + word + '</span>';
var wordArea = document.getElementById('wordArea');
this.displayWordButton = function() {
wordArea.innerHTML += this.wordHtml;
};
}
var myObject = new MyClass("sampleWord");
myObject.displayWordbutton();
It's adding all the buttons correctly but I can't get them to be clickable.
I've tried myObject.onclick = sampleFunction(); but it seems to activated the click event when the object is created and not when actually clicked.
I've tried adding an onclick attribute directly to the span in the class, but it doesn't function.