What's wrong here? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

22nd Mar 2024, 10:15 AM
Web Developer AD
5 Answers
+ 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
22nd Mar 2024, 10:39 AM
Freddyz Montilla
Freddyz Montilla - avatar
+ 2
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.
26th Mar 2024, 6:46 PM
🇮🇱 Radin Masiha 🇮🇱
🇮🇱 Radin Masiha 🇮🇱 - avatar
+ 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
22nd Mar 2024, 10:31 AM
Freddyz Montilla
Freddyz Montilla - avatar
+ 1
Thanks Freddyz Montilla it worked . 😊
22nd Mar 2024, 10:44 AM
Web Developer AD
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.
22nd Mar 2024, 10:33 AM
Web Developer AD