<button>: The Button element
The <button> HTML element is an interactive element activated by a user with a mouse, keyboard, finger, voice command, or other assistive technology. Once activated, it then performs an action, such as submitting a form or opening a dialog.
By default, HTML buttons are presented in a style resembling the platform the user agent runs on, but you can change buttons’ appearance with CSS.
Try it
Attributes
This element’s attributes include the global attributes.
This Boolean attribute specifies that the button should have input focus when the page loads. Only one element in a document can have this attribute.
This attribute on a <button> is nonstandard and Firefox-specific. Unlike other browsers, Firefox persists the dynamic disabled state of a <button> across page loads. Setting autocomplete=»off» on the button disables this feature; see Firefox bug 654072.
This Boolean attribute prevents the user from interacting with the button: it cannot be pressed or focused.
Firefox, unlike other browsers, persists the dynamic disabled state of a <button> across page loads. To control this feature, use the autocomplete attribute.
The <form> element to associate the button with (its form owner). The value of this attribute must be the id of a <form> in the same document. (If this attribute is not set, the <button> is associated with its ancestor <form> element, if any.)
This attribute lets you associate <button> elements to <form> s anywhere in the document, not just inside a <form> . It can also override an ancestor <form> element.
The URL that processes the information submitted by the button. Overrides the action attribute of the button’s form owner. Does nothing if there is no form owner.
If the button is a submit button (it’s inside/associated with a <form> and doesn’t have type=»button» ), specifies how to encode the form data that is submitted. Possible values:
- application/x-www-form-urlencoded : The default if the attribute is not used.
- multipart/form-data : Used to submit <input> elements with their type attributes set to file .
- text/plain : Specified as a debugging aid; shouldn’t be used for real form submission.
If this attribute is specified, it overrides the enctype attribute of the button’s form owner.
If the button is a submit button (it’s inside/associated with a <form> and doesn’t have type=»button» ), this attribute specifies the HTTP method used to submit the form. Possible values:
- post : The data from the form are included in the body of the HTTP request when sent to the server. Use when the form contains information that shouldn’t be public, like login credentials.
- get : The form data are appended to the form’s action URL, with a ? as a separator, and the resulting URL is sent to the server. Use this method when the form has no side effects, like search forms.
If specified, this attribute overrides the method attribute of the button’s form owner.
If the button is a submit button, this Boolean attribute specifies that the form is not to be validated when it is submitted. If this attribute is specified, it overrides the novalidate attribute of the button’s form owner.
This attribute is also available on <input type=»image»> and <input type=»submit»> elements.
If the button is a submit button, this attribute is an author-defined name or standardized, underscore-prefixed keyword indicating where to display the response from submitting the form. This is the name of, or keyword for, a browsing context (a tab, window, or <iframe> ). If this attribute is specified, it overrides the target attribute of the button’s form owner. The following keywords have special meanings:
- _self : Load the response into the same browsing context as the current one. This is the default if the attribute is not specified.
- _blank : Load the response into a new unnamed browsing context — usually a new tab or window, depending on the user’s browser settings.
- _parent : Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self .
- _top : Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self .
The name of the button, submitted as a pair with the button’s value as part of the form data, when that button is used to submit the form.
Turns a <button> element into a popover control button; takes the ID of the popover element to control as its value. See the Popover API landing page for more details.
Specifies the the action to be performed on a popover element being controlled by a control <button> . Possible values are:
The button will hide a shown popover. If you try to hide an already hidden popover, no action will be taken.
The button will show a hidden popover. If you try to show an already showing popover, no action will be taken.
The button will toggle a popover between showing and hidden. If the popover is hidden, it will be shown; if the popover is showing, it will be hidden. If popovertargetaction is omitted, «toggle» is the default action that will be performed by the control button.
The default behavior of the button. Possible values are:
- submit : The button submits the form data to the server. This is the default if the attribute is not specified for buttons associated with a <form> , or if the attribute is an empty or invalid value.
- reset : The button resets all the controls to their initial values, like <input type=»reset»>. (This behavior tends to annoy users.)
- button : The button has no default behavior, and does nothing when pressed by default. It can have client-side scripts listen to the element’s events, which are triggered when the events occur.
Defines the value associated with the button’s name when it’s submitted with the form data. This value is passed to the server in params when the form is submitted using this button.
Notes
A submit button with the attribute formaction set, but without an associated form does nothing. You have to set a form owner, either by wrapping it in a <form> or set the attribute form to the id of the form.
<button> elements are much easier to style than <input> elements. You can add inner HTML content (think <i> , <br> , or even <img> ), and use ::after and ::before pseudo-elements for complex rendering.
If your buttons are not for submitting form data to a server, be sure to set their type attribute to button . Otherwise they will try to submit form data and to load the (nonexistent) response, possibly destroying the current state of the document.
While <button type=»button»> has no default behavior, event handlers can be scripted to trigger behaviors. An activated button can perform programmable actions using JavaScript, such as removing an item from a list.
Examples
Accessibility concerns
Icon buttons
Buttons that only show an icon to represent do not have an accessible name. Accessible names provide information for assistive technology, such as screen readers, to access when they parse the document and generate an accessibility tree. Assistive technology then uses the accessibility tree to navigate and manipulate page content.
To give an icon button an accessible name, put text in the <button> element that concisely describes the button’s functionality.
Examples
Result
If you want to visually hide the button’s text, an accessible way to do so is to use a combination of CSS properties to remove it visually from the screen, but keep it parsable by assistive technology.
However, it is worth noting that leaving the button text visually apparent can aid people who may not be familiar with the icon’s meaning or understand the button’s purpose. This is especially relevant for people who are not technologically sophisticated, or who may have different cultural interpretations for the icon the button uses.
Size and Proximity
Interactive elements such as buttons should provide an area large enough that it is easy to activate them. This helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers. A minimum interactive size of 44×44 CSS pixels is recommended.
Proximity
Large amounts of interactive content — including buttons — placed in close visual proximity to each other should have space separating them. This spacing is beneficial for people who are experiencing motor control issues, who may accidentally activate the wrong interactive content.
Spacing may be created using CSS properties such as margin .
ARIA state information
To describe the state of a button the correct ARIA attribute to use is aria-pressed and not aria-checked or aria-selected . To find out more read the information about the ARIA button role.
Firefox
Firefox will add a small dotted border on a focused button. This border is declared through CSS in the browser stylesheet, but you can override it to add your own focused style using button::-moz-focus-inner .
If overridden, it is important to ensure that the state change when focus is moved to the button is high enough that people experiencing low vision conditions will be able to perceive it.
Color contrast ratio is determined by comparing the luminosity of the button text and background color values compared to the background the button is placed on. In order to meet current Web Content Accessibility Guidelines (WCAG), a ratio of 4.5:1 is required for text content and 3:1 for large text. (Large text is defined as 18.66px and bold or larger, or 24px or larger.)
Clicking and focus
Whether clicking on a <button> or <input> button types causes it to (by default) become focused varies by browser and OS. Most browsers do give focus to a button being clicked, but Safari does not, by design.
How To: HTML Canvas Buttons
![]()
In this tutorial, I will walk you through creating interactive buttons on the HTML5 canvas. This tutorial is split up into three sections: Getting Familiarized with the Starter Code, Creating a Button Class, and Adding Event Listeners to the Canvas.
For this tutorial, I will assume a basic understanding of both JavaScript and HTML. While a thorough knowledge of HTML is not necessary, we will be using a base index.html file as well as basic HTML events.
The code snippets in this tutorial are written in TypeScript as it more clearly shows the types of variables and functions which will hopefully minimize confusion. If you are new to TypeScript or would prefer to see the code in pure JavaScript, all source code from this tutorial can be found at this git repo.
Now, onto the tutorial…
Getting Familiarized with the Starter Code:
The starter code for this project can be found here. I have created a basic index.html file with a head and a body. Inside the body, you can find the canvas we will be drawing on, and a link to our JavaScript file:
In our main.js file, I have laid out the basic structure of a canvas update loop:
The init function serves as a place to setup (initialize) any variables for the program, while the update function provides a place to update the scene and redraw every frame.
I went ahead and added to the update loop so that it draws a black background and draws the initial version of our button:
We are now able to see a black canvas with an orange ‘button’ on it:
Creating a Button Class:
I could teach you how to create a button at a specific location with a specific size and handle clicks for that area of the screen, but that wouldn’t be very scalable. Instead, I will walk you through the process of creating a container class for our button so we can easily create many buttons anywhere on the screen (and even allow for a moving button or one that grows and shrinks).
First, it would be good to decide what variables our button class will contain. Another way to think about this is: what might differ from button to button?
The features I have decided that vary between buttons are: text, button color, text color, position, and size. From this, we can create the following fields for our class.
Next, we should make a constructor for our button class. Since the main things that define separate buttons to me is the text and the styling, I made the constructor with only those parameters. I created separate functions for setting the position and size of the button (which also allows for easier animating of the buttons).
This class now holds all of our data for a button, but how do we draw it? We could access all of its fields individually, and draw it using the code we had in main.js prior, but again, that wouldn’t be very scalable. Let’s create a draw method in Button so each button knows how to draw itself.
Here I have adapted the drawing code from main.js to use the fields in our class instead of the hardcoded values:
Now in our main.js it is time to create an instance of our Button class. We will initialize our button in the init function:
All we need to do now in order to draw our button is to call our button’s draw method in the update loop:
If we look at the result, we can see that our button is drawing once again and we can tweak the values in our developer console and watch it update live.
If you are following along, it might be a good exercise to try implementing button borders (ie. color, thickness, etc…) yourself.
Adding Event Listeners to the Canvas:
Now we’re getting to the main show… almost.
Before we add our button clicks, I suggest we think about the way we call draw on our button. The way we have it currently, we will need to call that function for every button in our scene. Instead of cluttering our code with all of these button.draw(c); lines, let’s create an array to store our buttons.
This way we are able to cleanly loop through all of our buttons and call their draw methods:
In order to add functionality to our buttons, we will need to add two things to our Button class. The first is a method that checks if a given position is within the bounds of the button (this will make it very easy to check if the mouse clicked on a button).
The second is a function that should be called when the button is clicked (aka what the button does). Since this function will vary for each button, I will treat it as a field of Button with the type of a void lambda function.
For our ‘Start Game’ button, I made the following lambda to log “Start Game!” whenever the button is clicked:
Now we are ready to add our event listener. Our event listener will detect anytime the canvas is clicked, determine the mouse position on the canvas, and call the onClick method of all (if any) buttons that the mouse was over when the click occurred.
Now we can see the message “Start Game!” in our console whenever we click our button.
Wrapup:
If you would like an exercise to try to build off of what I covered, my suggestions would be to make buttons change color when hovered over or clicked on. If you are not very familiar with HTML Events, this may be a helpful resource.
All source code can be found here, and live versions of each of the three stages of development can be found here.
HTML <button> Tag
Inside a <button> element you can put text (and tags like <i> , <b> , <strong> , <br> , <img> , etc.). That is not possible with a button created with the <input> element!
Tip: Always specify the type attribute for a <button> element, to tell browsers what type of button it is.
Tip: You can easily style buttons with CSS! Look at the examples below or visit our CSS Buttons tutorial.
Browser Support
| Element | |||||
|---|---|---|---|---|---|
| <button> | Yes | Yes | Yes | Yes | Yes |
Attributes
| Attribute | Value | Description |
|---|---|---|
| autofocus | autofocus | Specifies that a button should automatically get focus when the page loads |
| disabled | disabled | Specifies that a button should be disabled |
| form | form_id | Specifies which form the button belongs to |
| formaction | URL | Specifies where to send the form-data when a form is submitted. Only for type="submit" |
| formenctype | application/x-www-form-urlencoded multipart/form-data text/plain |
Specifies how form-data should be encoded before sending it to a server. Only for type="submit" |
| formmethod | get post |
Specifies how to send the form-data (which HTTP method to use). Only for type="submit" |
| formnovalidate | formnovalidate | Specifies that the form-data should not be validated on submission. Only for type="submit" |
| formtarget | _blank _self _parent _top framename |
Specifies where to display the response after submitting the form. Only for type="submit" |
| name | name | Specifies a name for the button |
| type | button reset submit |
Specifies the type of button |
| value | text | Specifies an initial value for the button |
Global Attributes
Event Attributes
The <button> tag also supports the Event Attributes in HTML.
More Examples
Example
Use CSS to style buttons:
<!DOCTYPE html>
<html>
<head>
<style>
.button <
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
cursor: pointer;
>
Example
Use CSS to style buttons (with hover effect):
<!DOCTYPE html>
<html>
<head>
<style>
.button <
border: none;
color: white;
padding: 16px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin: 4px 2px;
transition-duration: 0.4s;
cursor: pointer;
>
.button1 <
background-color: white;
color: black;
border: 2px solid #4CAF50;
>
.button1:hover <
background-color: #4CAF50;
color: white;
>
.button2 <
background-color: white;
color: black;
border: 2px solid #008CBA;
>
.button2:hover <
background-color: #008CBA;
color: white;
>
<button>¶
Тег <button> (от англ. button — кнопка) создаёт на веб-странице кнопки и по своему действию напоминает результат, получаемый с помощью <input> (с атрибутом type=»button | reset | submit» ).
В отличие от этого элемента, <button> предлагает расширенные возможности по созданию кнопок. Например, на подобной кнопке можно размещать любые элементы HTML, в том числе изображения. Используя стили можно определить вид кнопки путём изменения шрифта, цвета фона, размеров и других параметров.
- button
Синтаксис¶
Закрывающий тег обязателен.
Атрибуты¶
Также для этого тега доступны универсальные атрибуты.
autofocus¶
Атрибут autofocus устанавливает, что кнопка получает фокус после загрузки страницы. Такую кнопку можно нажать сразу без перевода на неё фокуса, например, с помощью клавиатуры.
Синтаксис
Значения
Значение по умолчанию
По умолчанию это значение выключено.
disabled¶
Блокирует доступ к кнопке и её изменение. Она в таком случае отображается серым цветом и недоступна для активации пользователем. Кроме того, такая кнопка не может получить фокус путём нажатия на клавишу Tab , мышью или другим способом. Тем не менее, такое состояние кнопки можно изменять через скрипты. Значение блокированной кнопки не передаётся на сервер.
Синтаксис
Значения
Значение по умолчанию
По умолчанию это значение выключено.
Связывает кнопку с формой по её идентификатору. Такая связь необходима в случае, когда кнопка не располагается внутри элемента <form> , например, при создании её программно.
Синтаксис
Значения
Идентификатор формы (значение атрибута id элемента <form> ).
Значение по умолчанию
formaction¶
Определяет адрес обработчика формы — это программа, которая получает данные формы и производит с ними желаемые действия. Атрибут formaction по своему действию аналогичен атрибуту action элемента <form> . Если одновременно указать action и formaction , то при нажатии на кнопку атрибут action игнорируется и данные пересылаются по адресу, указанному в formaction .
Синтаксис
Значения
formenctype¶
Устанавливает способ кодирования данных формы при их отправке на сервер. Обычно явно указывается в случае, когда используется поле для отправки файла ( input type=»file» ). Этот атрибут по своему действию аналогичен атрибуту enctype элемента <form> .
Синтаксис
Значения
application/x-www-form-urlencoded Вместо пробелов ставится + , символы вроде русских букв кодируются их шестнадцатеричными значениями (например, %D0%9F%D0%B5%D1%82%D1%8F вместо Петя). multipart/form-data Данные не кодируются. Это значение применяется при отправке файлов. text/plain Пробелы заменяются знаком + , буквы и другие символы не кодируются.
Значение по умолчанию
- application/x-www-form-urlencoded
formmethod¶
Атрибут сообщает браузеру, каким методом следует передавать данные формы на сервер.
Синтаксис
Значения
Различают два метода — GET и POST.
GET Этот метод предназначен для передачи данных формы непосредственно в адресной строке в виде пар « имя=значение », которые добавляются к адресу страницы после вопросительного знака и разделяются между собой амперсандом (символ & ). Полный адрес к примеру будет http://site.ru/doc/?name=Vasya&password=pup . Объём данных в методе ограничен 4 Кб. POST Посылает на сервер данные в запросе браузера, объём пересылаемых данных ограничен лишь настройками сервера.
formnovalidate¶
Отменяет встроенную проверку данных введённых пользователем в форме на корректность при нажатии на кнопку. Такая проверка делается браузером автоматически при отправке формы на сервер для полей <input type=»email»> , <input type=»url»> , а также при наличии атрибута pattern или required у элемента <input> .
Синтаксис
Значения
Значение по умолчанию
По умолчанию этот атрибут выключен.
formtarget¶
Определяет имя фрейма, в которое будет загружаться результат, возвращаемый обработчиком формы, в виде HTML-документа.
Синтаксис
Значения
В качестве значения используется имя фрейма, заданное атрибутом name элемента <iframe> . Если установлено несуществующее имя, то будет открыта новая вкладка. В качестве зарезервированных значений можно указывать следующие.
_blank Загружает страницу в новую вкладку браузера. _self Загружает страницу в текущую вкладку. _parent Загружает страницу во фрейм-родитель; если фреймов нет, то это значение работает как _self . _top Отменяет все фреймы и загружает страницу в полном окне браузера; если фреймов нет, то это значение работает как _self .
Определяет уникальное имя кнопки. Как правило, это имя используется при отправке значения кнопки на сервер или для доступа к кнопке через скрипты.
Синтаксис
Значения
В качестве имени используется набор символов, включая числа и буквы. JavaScript чувствителен к регистру, поэтому при обращении к элементу по имени соблюдайте ту же форму написания, что и в атрибуте name .
Значение по умолчанию
Определяет тип кнопки, который устанавливает её поведение в форме. По внешнему виду кнопки разного типа никак не различаются, но у каждой такой кнопки свои функции.
Синтаксис
Значения
button Обычная кнопка. reset Кнопка для очистки введённых данных формы и возвращения значений в первоначальное состояние. submit Кнопка для отправки данных формы на сервер. menu Открывает меню, созданное с помощью элемента <menu> .
Значение по умолчанию
- submit
value¶
Определяет значение кнопки, которое будет отправлено на сервер. На сервер отправляется пара « имя=значение », где имя задаётся атрибутом name элемента <button> , а значение — атрибутом value . Значение может как совпадать с текстом на кнопке, так быть и самостоятельным. Также атрибут value применяется для доступа к данным через скрипты.