I have this code for making a button programatically
function makeButton(text, classList, parent, onClick){
let button = document.createElement('button')
button.classList = classList
button.innerHTML = text
button.onclick = onClick
parent.appendChild(button)
return button
}
it has functioned fine so far in situations like this where I’m adding a button to a DOM element that has already been instantiated
let diag = new PopupModal()
makeButton('CANCEL', 'btn btn-sm btn-secondary', diag.footer, function() {
diag.closeFunc()
})
however I’d like to use it in a new way where the button’s function is added during the constructor of the class for example
function makeElement(type, classList, parent){
let el = document.createElement(type)
el.classList = classList
parent.appendChild(el)
return el
}
class complexForm_newProductWithType{
constructor(doc){
this.container = document.createElement('div')
this.container.classList = 'container'
this.doc = doc
this.identifiers = makeElement('div', 'row', this.container)
this.descriptors = makeElement('div', 'row', this.container)
this.options = makeElement('div', 'row', this.container)
this.buttons = makeElement('div', 'row', this.container)
...
this.button_save = makeButton('SAVE', 'btn btn-sm btn-success', this.buttons, function() {
console.log('save')
})
this.button_cancel = makeButton('CANCEL', 'btn btn-sm btn-secondary', this.buttons, function() {
console.log('cancel')
})
}
}
function addForm(doc){
form = new complexForm_newProductWithType(doc)
document.getElementById("doc-selection").innerHTML = form.container.outerHTML
}
in this scenario the button is created with the correct style and text but the event does not fire. I’ve tried changing the line onclick = onClick
to button.addEventListener('click', onClick, false)
with no effect
2
Answers
Thanks to Xiahaolin I realized my issue. Since his writing of my code functioned I looked to see what was different. Which was that he used
document.body.appendChild
I had usedinnerHTML
to insert my dom elements. changing it toappendChild(form.container)
fixed my issue. Thank you for your help!I tested your basic code,the code is runnable, Can you provide console information?