HTML buttons are used to create interactive elements on a web page. They are created using the <button> element, which can be placed inside a form or on its own. When a user clicks on a button, a specified JavaScript function is executed. This function can perform a variety of actions, such as submitting a form, triggering a animation, or displaying a message.
Buttons can have different types and appearance based on the use case. By default the button is a submit button but it can also be type of 'reset' or 'button' which will just trigger a javascript function. And they can have different attributes that can be used to style the button, such as the class and id attributes, which can be used to apply CSS styles to the button.
Here's an example of a basic HTML button:
<button>Click me!</button>
You can use JavaScript to specify what should happen when a button is clicked. For example, you could create a JavaScript function that displays an alert message when a button is clicked:
<button onclick="alert('Button clicked!')">Click me!</button>
You can also use JavaScript to assign an event listener to the button, which will listen for a click event and then execute a specified function when the button is clicked. Here's an example:
<button id="my-button">Click me!</button> <script> document.getElementById("my-button").addEventListener("click", function() { alert("Button clicked!"); }); </script>
Another way to use buttons is with forms where it can be used to submit data. Here is an example of a form with a submit button:
<form> <label for="input-field">Enter your name:</label> <input type="text" id="input-field" name="name"> <button type="submit">Submit</button> </form>
In this example, the form has a text input field and a submit button. When the user enters their name and clicks the button, the form data will be sent to the server for processing.
In summary, HTML buttons are used to create interactive elements on web pages that can be used to perform actions such as submitting forms, triggering animations, and displaying messages when clicked.