+ 1
What's wrong here?
I was practicing functions in a class in js but it's not working on clicking the button but is automatically alerting when the window loads. Please help me Here's the code: https://sololearn.com/compiler-playground/Wyt0Hr9wsw9G/?ref=app
5 odpowiedzi
+ 3
It looks like your button is missing the JavaScript needed to trigger an alert. Here's how you can add a simple script to make the button work:
html
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script>
// Wait for the DOM to load
document.addEventListener('DOMContentLoaded', (event) => {
// Get the button element
var btn = document.getElementById('btn');
// Add click event listener to the button
btn.addEventListener('click', function() {
alert('Button clicked!');
});
});
</script>
</head>
<body>
<button id="btn">alert</button>
</body>
</html>
In this code, the `DOMContentLoaded` event ensures that the script runs after the entire page is loaded, and the `click` event listener is added to the button with the ID `btn`. When the button is clicked, it will trigger the `alert` function. Remember to place the scri
+ 3
Just sth to add to Freddyz Montilla
It is better to use window.onload (or addEventListener("load",...)) instead of DOMContentLoaded cuz onload makes sure all the assets and images are loaded, but DOMContentLoaded only focuses on the content.
+ 1
So your problem is when pressed run it says hello idk what is the problem. I will fix it when i understand it. Comment me pls so I can understand what you ment
+ 1
Thanks Freddyz Montilla it worked . 😊
0
Freddyz Montilla the problem is that I want it to alert after clicking the button but it automatically alerts when the window loads and doesn't when you click the button.