Buttons in web pages are used to provide interactive user experience. As a rule, if the response to a button click does not require sending data to the server, then the interaction is implemented using JavaScript scripts. The methods for invoking the corresponding JavaScript code may vary - below are several possible options for different types of buttons.
Instructions
Step 1
If the display of a button in a web page is organized using the button tag, then the JavaScript code can be placed in the onclick attribute. For example, like this: button Of course, it is not advisable to put large enough code directly into the button tag - it is better to design it as a function, and put only the code for calling this function into the onclick attribute. For example:
function showAlert () {
alert ('Button clicked!')
}
button
Step 2
If the button is rendered through one of the input tag variations (submit, reset, button, or image), then the same onclick attribute can be used. For example, for a button to clear form fields (reset), the code might look like this: If you want only JavaScript to be executed when the button is clicked, and the default action does not occur, add the return command to the function or directly to the onclick attribute false. For example:
Step 3
If you need to organize a response to clicking a button of the submit type, then, in addition to the above method using the onclick attribute, you can use the properties of the form tag to which this button belongs. The corresponding function call can be placed in the onsubmit attribute of the form tag. For example:
Step 4
If a button is not a form element, but just a graphic element (img tag), then the standards for it also allow the use of the onclick attribute. For example:
Step 5
If the button is a hyperlink, then you should not use the attributes of the button itself; it is better to use the properties of the link tag. You can, as in the previous options, use the onclick tag. For example: And you can replace the address in the href attribute with a function call. For example, like this: