In this example we will cover how to create a simple web button for web. It is just for showing how to add a button element and listen to the click event happening when users clicks on it. For that, we are going to use alert feature to show how button behaves.
In this example we will need only two files, because we are not going to use any styles from .css.
In our starting point, index.html file we need to put header, text beneath the header and in the end our button element:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<!DOCTYPE html> <html lang="en"> <h2>Web Button Example</h2> <p>This example uses the show how to make button to be shown on web page</p> <head> <meta charset="UTF-8"> <link href="https://fonts.googleapis.com/css?family=Lato:100,300,600" rel="stylesheet" type="text/css"> <link href="http://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" rel="stylesheet" type="text/css"> <link type="text/css" rel="stylesheet" href="style.css"> <title>Button</title> </head> <body> <div class="container"> <button id="myButton" type="button">BUTTON</button> </div> <script src="app.js"></script> </body> </html> |
The second feature that we need to add is the functionality of the button that goes in to app.js file, that we have added in the <script> tag in our previously created index.html file. This links both of the files. For this example we are going to bind the button using the id of it with getElementById() function. In our case that is myButton. After that, we are going to call .addEventListener() function. We need to pass the action to it, and thats “click” and what we want our button to do after it has been clicked. For that we pass a function that we are creating separately from the button listener. As a bonus, we add console.log(‘message’) to show in our console (F12 for Chrome users) that our code works for testing
1 2 3 4 5 6 7 |
console.log('Button click'); document.getElementById('myButton').addEventListener("click", onClick); function onClick() { alert ("Button Clicked"); } |
Saved as a favorite!, I really like your blog!