Button
Button
Overview
In most circumstances, using a native HTML <button>
or <input type="submit">
element is a better choice than creating a custom ARIA button, but there are use cases where an ARIA button can be appropriate, such as when styling a standard <button>
is too difficult in the range of target browsers under certain circumstances, or when retrofitting legacy markup that could be problematic to convert to standard <button>
elements.
Turn on a screen reader to experience this example in action.
HTML Source Code
<div>
<div role="button" id="div-button" class="button" tabindex="0" ><div> Button</div>
<a role="button" id="a-button" class="button" tabindex="0" ><a> Button</a>
<button type="button" id="native-button">Native Button</button>
</div>
JavaScript Source Code
window.addEventListener('load', function () {
document.getElementById('div-button').addEventListener('click', divButtonClicked);
document.getElementById('a-button').addEventListener('click', aTagButtonClicked);
document.getElementById('div-button').addEventListener('keydown', keydownButtonHandler);
document.getElementById('a-button').addEventListener('keydown', keydownButtonHandler);
document.getElementById('native-button').addEventListener('click', nativeButtonClicked);
});
function divButtonClicked()
{
alert("Div Button clicked.");
}
function aTagButtonClicked()
{
alert("A Tag Button clicked.");
}
function nativeButtonClicked()
{
alert("Native Button clicked.");
}
function keydownButtonHandler(event) {
if (event.keyCode === 32) {
event.preventDefault();
event.target.click();
}
else if (event.keyCode === 13) {
event.preventDefault();
event.target.click();
}
}
CSS Source Code
.button {
padding: 5px 10px;
display: inline-block;
border: 2px solid gray;
margin: 2px;
}
button {
padding: 9px 12px;
font-size: 16px;
margin: 2px;
}
.button:hover{
background-color: #aed9ee;
}
.button:focus{
margin: 2px;
outline: 2px solid blue;
}