user12287130
user12287130

Reputation: 7

Function inside of another function only works once

In my html page I have a button that creates another button when clicked. That created button creates a paragraph when clicked but this one only works once. It's two functions inside of each other which, I think, is the cause of the problem. What would be a better way of doing this?

Writing the inner function separate from the containing one gives me an error as the id the inner one tries to access doesn't exist until the containing one is called/the original button is clicked.

// Containing function

document.getElementById("buttonCreator").onclick=function() {

    targetElement.innerHTML = (""); // Reset the main divs contents
    var button1 = document.createElement("button"); // Create a button
    var bContent = document.createTextNode("Click me!");
    button1.appendChild(bContent);
    button1.setAttribute("id", "createdButton"); // Give the button an id 
    targetElement.appendChild(button1);

// Inner function - this only works once

    document.getElementById("createdButton").onclick=function() { 

        targetElement.innerHTML = targetElement.innerHTML 
        + "<br> <br>" 
        + ("You clicked the created button!);
    }
}

There are no errors.

Upvotes: 0

Views: 80

Answers (2)

KletskovG
KletskovG

Reputation: 550

You can try to create another function to handle this.

document.getElementById("buttonCreator").onclick=function() {

    targetElement.innerHTML = (""); // Reset the main divs contents
    var button1 = document.createElement("button"); // Create a button
    var bContent = document.createTextNode("Click me!");
    button1.appendChild(bContent);
    button1.setAttribute("id", "createdButton"); // Give the button an id 
    targetElement.appendChild(button1);

    button1.addEventListener('click', () => {
        clickCreatedButton(targetElement, button1);
    })
}

function clickCreatedButton(targetElement, button) {
    button.addEventListener('click', () => {
        targetElement.innerHTML = targetElement.innerHTML 
        + "<br> <br>" 
        + ("You clicked the created button!");
    })
}

Upvotes: 0

Kl&#237;mačka
Kl&#237;mačka

Reputation: 281

The problem is in targetElement.innerHTML = targetElement.innerHTML where you replace the original HTML which has the DOM event (click) attached with a new HTML and do not attach the event again.

Upvotes: 1

Related Questions