I am trying to make a button that triggers the <p>
element to be changed from Boing! to Bummtschak!
When the page loads Bummtschak! is displayed, although I did not click and nothing happens in the following click event. I do not know what I am doing wrong.
const para = document.querySelector("p");
const btn = document.getElementById("btn");
btn.addEventListener('click', backTo());
function backTo() {
if (para.textContent == "Boing!") {
para.textContent = "Bummtschak!";
}else{
para.textContent = "Bummtschak!";
}
}
The html is:
...
<script src="script.js" defer></script>
</head>
<body>
<button id="btn"></button>
<p>Boing!</p>
</body>
</html>
You should not have the ()
in the addEventListener
const para = document.querySelector("p");
const btn = document.getElementById("btn");
btn.addEventListener('click', backTo);
function backTo() {
if (para.textContent == "Boing!") {
para.textContent = "Bummtschak!";
}else{
para.textContent = "Bummtschak!";
}
}
<button id="btn"></button>
<p>Boing!</p>