Welcome folks today in this blog post we will be looking at an very simple example of button onclick attribute
to attach onclick event listener on button click in browser using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to make an index.html
file and copy paste the following code
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script> function showMessage(){ alert("Show Message") } </script> </head> <body> <button onclick="showMessage()">Click Button</button> </body> </html> |
As you can see in the above code we are attaching the onclick
attribute to the button
and inside it we are calling the showMessage()
method to show the alert
popup message.
Using the AddEventListener() Method
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button id="button">Click Button</button> </body> <script> document.getElementById('button').addEventListener('click', () => { alert("hello world") }) </script> </html> |
As you can see we are using the addEventListener()
method to attach the click
event to the button. And inside it we are showing the alert
popup box.