The <button> element will display a clickable button in the browser. It is a generic element which we use mostly in forms.
As always, it has a default browser style that imitates a button. It is an element with meaning, so it has an accessible function.
Types of the Button
The button is an accessible element, assistive technologies will recognize it. When we interact with it, the browsers handle many things for us (states, events).
As I said earlier, we usually attach it to a form (as a submit button), but we can also use it elsewhere. Like if you have a mobile menu (or any menu hidden), you want to open on a click. In this case, you should use a button element (with aria-expanded at least) to mockup the toggle control.
If you declare the <button> tag inside a form, it will fire the submit event, outside of it won’t.
<button type="submit">Submit</button> <button type="reset">Reset</button> <button type="button">Button</button>
We can declare it’s behavior with the type attribute:
- type=”submit”: will submit the form data to the server. It is the default behavior if it is placed inside a form.
- type=”reset”: will reset the form values if placed inside a form.
- type=”button”: will be function as a generic button.
A Button or a Link
By design, we have to differentiate the links and buttons. The reason is that the expected behavior differs. When we click on a link, we expect to navigate to another post. When we click on a button, we hope for an on-page action (like sending a form).
So it is not the same the use the <a> and the <button> element. Both of them have their function use it properly because it can mean a lot.
<a href="/about.html">Navigate to about page</a> <button>Submit form</button>
The <button> element also has similar parameters like any input:
- we can disable it with the disabled attribute,
- we can declare a name attribute,
- or use autofocus on it.
A Button or an Input Element
We can send a form in two way (with native element): <button> and <input type=”submit”>. Using the input tag which is an older solution that can feel a bit weird because that is an input element.
<button>Submit</button> <input type="submit" value="Submit"/>
The <button> is semantically correct in this case and has other advantages like that it is not a self-closing element. This means that we can add anything between the opening and closing tags. Using the input, we have only the option to add a caption.
Need a web developer? Maybe we can help, get in touch!