Skip to content
Advertisement

Adding onclick functions to buttons within JavaScript

I’m trying to make a quiz in JavaScript. Basically my code has a button that starts the quiz, and when I click it, I remove the button and add four more. To each of the buttons I added an onclick attribute.

responseOne.onclick = changeScore();

I expect this line to run the changeScore function when I click on the ‘responseOne’ button. The problem is when I run the function startQuiz(), the function changeScore runs four times before even removing and adding any of the buttons. What’s wrong with my code?

Also I’m really new so if any of my other code is inefficient or something, constructive criticism is always welcome too 🙂

function startQuiz() {

//remove the start quiz button
    var element = document.getElementById("dummy")
    element.parentNode.removeChild(element);
//change the h1 and h2 html tags to the question number and question
    h1.innerHTML = title[questionNumber];
    h2.innerHTML = questions[questionNumber];
//create buttons and give them bootstrap and onclick functions, appending them to empty divs
    var responseOne = document.createElement("button");
    responseOne.innerHTML = responseA[questionNumber];
    responseOne.onclick = changeScore();
    responseOne.classList.add("btn");
    responseOne.classList.add("btn-primary");
    document.getElementById("button1").appendChild(responseOne);

    var responseTwo = document.createElement("button");
    responseTwo.innerHTML = responseB[questionNumber];
    responseTwo.onclick = changeScore();
    responseTwo.classList.add("btn");
    responseTwo.classList.add("btn-danger");
    document.getElementById("button2").appendChild(responseTwo);

    var responseThree = document.createElement("button");
    responseThree.innerHTML = responseC[questionNumber];
    responseThree.onclick = changeScore();
    responseThree.classList.add("btn");
    responseThree.classList.add("btn-warning");
    document.getElementById("button3").appendChild(responseThree);

    var responseFour = document.createElement("button");
    responseFour.innerHTML = responseD[questionNumber];
    responseFour.onclick = changeScore();
    responseFour.classList.add("btn");
    responseFour.classList.add("btn-success");
    document.getElementById("button4").appendChild(responseFour);
}

function changeScore() {
    alert("changeScore function is running");
}

Advertisement

Answer

although there pretty good ways to do that in JavaScript. But, in this case automatic running changeScore() can be handled this way.

responseOne.onclick = changeScore();

replace above line with this

responseOne.onclick = changeScore;

do it for all responseOne,responseTwo, responseThree, and responseFour.

😃

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement