Laassari Laassari - 19 days ago 5
Javascript Question

JavaScript onclick event works only once

I am trying to make a simple HTML page that contains a paragraph with some classes and a button with a random predefined name that will be chosen from an array, and another paragraph to show the result.

I made a function that will check if the button's name exists as a class in the first paragraph if so it will write in the last paragraph "It exists.". If not it will show "No it doesn't.".

The function will be triggered when I click the button. The problem that it works only once. Here is the code



var mainParagraph = document.getElementById("test-paragraph"),
buttonCheck = document.getElementById("class-checker"),
resultContainer = document.getElementById("result-container");
// An array of possible names of the button
var buttonName = ["test", "two", "random", "fly", "false", "checked", "wrong", "last", "process", "end"],
x = Math.random() * 10,
z = Math.floor(x);
//change the button's name each time the button is clicked. "not working."
function butonClicked() {
'use strict';
buttonCheck.textContent = buttonName[z];
}
// function to check if button's name is the same as a class in the first paragraph
function checkTheClass() {
'use strict';
if(mainParagraph.classList.contains(buttonName[z])) {
resultContainer.textContent = "yes the class exists. It's : " + '"' + buttonName[z] + '"';
} else {
resultContainer.textContent = "No the class doesn't exists.";
}
}
// Trigger the function when the button is clicked
buttonCheck.onclick = function() {
'use strict';
butonClicked();
checkTheClass();
};

<html>

<body>
<p id="test-paragraph" class="test random checked work done process"> This is a random text to be use for the test
<br/> these are the classes: test, random, checked, work, done, process. </p>
<button id="class-checker">click!</button>
<p id="result-container">Here is the result</p>
</body>

</html>





I already checked these answers, but I still can't solve the problem:

Simple onclick event worked only once.

onclick event works only once in arctext script.

Here is the code in Codepen: http://s.codepen.io/Noureddine/debug/JbbBQX.

Ps: I don't know JQquery

Answer

It's not that your event is getting fired only once but the variable z is not updated each time so it keeps trying to grab the same index from your array.

buttonCheck.onclick = function () {
    'use strict';
    z = Math.floor(Math.rand() * 10);
    butonClicked();
    checkTheClass();

};