Add onclick event in javascript button

Asked

Viewed 125 times

-2

I’m trying to make a page that, when clicked, creates a button that when pressed it calls the function back in the history:

function goBack(){
window.history.back();
}
function criarBotao(){
    var botao = document.createElement("BUTTON");
    botao.innerHTML = "Voltar";
    document.body.appendChild(botao);
    botao.onclick = goBack();
}
window.onload = criarBotao();

The problem is that every time the page opens, the goBack() function happens automatically, without pressing the button. Could anyone help me? Thanks.

  • 2

    Should be botao.onclick = goBack; without parentheses. Writing the function name with parentheses will invoke it, you don’t want to invoke it, you just want to pass it to the event. The same goes for criarBotao, should be window.onload = criarBotao;

  • Thanks friend.

1 answer

2

The problem is that at the time you were adding the function goBack at the botao, was done wrong, can’t use parentheses () after the function as you did botao.onclick = goBack();, if not the function will be invoked.

The right then would be without parentheses, as in the lower part window.onload = criarBotao();, where the same mistake was made.

So your code would look like this:

function goBack(){
    window.history.back();
}
function criarBotao(){
    var botao = document.createElement("BUTTON");
    botao.innerHTML = "Voltar";
    document.body.appendChild(botao);
    botao.onclick = goBack;
}
window.onload = criarBotao;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.