How To Make A Button With A Code

Table of contents:

How To Make A Button With A Code
How To Make A Button With A Code

Video: How To Make A Button With A Code

Video: How To Make A Button With A Code
Video: HTML how to add buttons 🛎️ #9 2024, May
Anonim

When creating pages, it is sometimes necessary that when you click on the button placed in the page, some event programmed by the author occurs in the browser. To do this, you need to place JavaScript code in the generated document and bind it to the required button. Depending on the amount of code that is required to implement the intended event, you can use different ways to connect the button to the code.

How to make a button with a code
How to make a button with a code

Instructions

Step 1

Most often, JavaScript code calls are bound to the onclick event, that is, to the click on the left mouse button. If you don't need a lot of code to describe the action that should happen, then you can put it all right in the button tag. For example, to program the browser to show a simple message when a button is clicked, the JavaScript script would look like this: alert ('Code worked!') It only takes one statement and text. All this can be easily placed in the onclick event description of the button tag. In this case, the simplest HTML-code of the page might look like this:

Button with code

Button with code

Step 2

It is not practical to place more complex JavaScript code directly in the button tag. It's easier to make a separate function out of it, and put its call in the onclick event. For example, this might look like a function that displays a window containing the time of a button click: function getTime () {

var now = new date ();

alert ("The code worked in" + now.getHours () + ":" + now.getMinutes ());

} It should be placed in the header of the page (between the and tags). The complete code of the page with a call to this function bound to the button may look like this:

Function call button

function getTime () {

var now = new date ();

alert ("The code worked in" + now.getHours () + ":" + now.getMinutes ());

}

Function call button

Step 3

The same method should be used when clicking several different buttons should raise an event that can be described with the same JavaScript code. For example, you can slightly modify the previous function to add the identification of the pressed button to the message box: function getTime (btnString) {

var now = new date ();

alert (btnString + "clicked in" + now.getHours () + ":" + now.getMinutes ());

} The complete code of a page with three such buttons might look like this:

Three buttons with a function call

function getTime (btnString) {

var now = new date ();

alert (btnString + "clicked in" + now.getHours () + ":" + now.getMinutes ());

}

First button

Second button

Third button

Recommended: