Reputation: 41
So 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 class="text-box">
<h1>BLOG</h1>
</div>
<div class="buttons">
<button id="play"> OK </button>
</div>
<script src="music-player/scripts/app.js"></script>
</body>
</html>
Upvotes: 0
Views: 879
Reputation: 1
Because your index.html file inside music-player folder. You should change script source to "./scripts/app.js"
Upvotes: 0
Reputation: 17119
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>
Upvotes: 4
Reputation: 282
Update function name:
const btn = document.getElementById("play");
btn.addEventListener("click", alertMessage);
function alertMessage() {
alert("Pls tell me youre working...");
}
<html>
<body>
<div class="text-box">
<h1>BLOG</h1>
</div>
<div class="buttons">
<button id="play"> OK </button>
</div>
<script src="music-player/scripts/app.js"></script>
</body>
</html>
Upvotes: 1
Reputation: 94
change the name of the function from alert to something else or you can add directly add onClick="function()" in button tag it self
Upvotes: -1