Home > other >  Button doesn't do anything when clicked
Button doesn't do anything when clicked

Time:10-02

enter image description hereSo I have a HTML file with a button, and an external js file that should have some functionality. But it doesn't work. Here's the code:

HTML full code:

const btn = document.getElementById("play");

btn.addEventListener("click", alertMessage);

function alertMessage() {
  alert("Pls tell me youre working...");
}
<html>

<body>

  <div >
    <h1>BLOG</h1>
  </div>
  <div >
    <button id="play"> OK </button>
  </div>
  <script src="music-player/scripts/app.js"></script>
</body>

</html>

CodePudding user response:

Because that make Maximum call stack size because the alert inside the function will not refer to the default global alert but to the function itself which makes an infinity recursion, you need to change the function name.

const btn = document.getElementById("play");

btn.addEventListener("click", alertMessage);

function alertMessage()
{
  alert("Pls tell me youre working...");
}
<div class= "buttons">
    <button id="play"> OK </button>
    </div>
    <script src="music-player/scripts/app.js"></script>

If you used window.alert() and used function expression instead of a function declaration ( which overite the global alert ) it will work fine, but for sure it would better to change the function name to prevent conflicts.

const alert = () =>
{
  window.alert("Pls tell me youre working...");
}

const btn = document.getElementById("play");

btn.addEventListener("click", alert);
<div class= "buttons">
    <button id="play"> OK </button>
    </div>
    <script src="music-player/scripts/app.js"></script>

CodePudding user response:

Update function name:

const btn = document.getElementById("play");

btn.addEventListener("click", alertMessage);

function alertMessage() {
  alert("Pls tell me youre working...");
}
<html>

<body>

  <div >
    <h1>BLOG</h1>
  </div>
  <div >
    <button id="play"> OK </button>
  </div>
  <script src="music-player/scripts/app.js"></script>
</body>

</html>

CodePudding user response:

change the name of the function from alert to something else or you can add directly add onClick="function()" in button tag it self

  • Related