What happens when a button is clicked in JavaScript?
A click event, changing text and a counter.
All lessons · JavaScript lessons: learn from scratch
When a button is clicked
An event is something the user does. The most used one is a click. onclick is fine for a small example. In a separate script, addEventListener is the clearer way.
<button id="menimDuyme">Bas mənə</button>
<script>
const duyme = document.getElementById("menimDuyme");
duyme.addEventListener("click", function () {
alert("Düyməyə basdın!");
});
</script>Change the text and count
getElementById finds an element by its id. textContent changes that element's text. The page does not reload.
let say = 0;
const sayElementi = document.getElementById("say");
const duyme = document.getElementById("artir");
duyme.addEventListener("click", function () {
say = say + 1;
sayElementi.textContent = say;
if (say >= 5) {
document.getElementById("mesaj").textContent = "Sayğac 5-ə çatdı.";
}
});Questions
What is onclick? A short command that runs on a click. Enough for a small example.
What does addEventListener wait for? The first argument is the event name, such as click. The second is a function.
Why is an id needed? So JavaScript can find that element. It should not repeat on the page.
What does textContent change? The visible text of the element. Without reloading the page.