It seems like you are striving to make your content more accessible by incorporating the appropriate attributes and elements.
Every element on a webpage plays a specific role, especially in communicating with users who utilize assistive technologies. For instance, an <img>
element signifies an image, but if it is meant to act as a button, its role should be specified as such.
By utilizing a <button>
element, you can ensure automatic accessibility features such as focus and response to the Space or Enter keys. Adding an aria-label
attribute provides a clear and accessible name for users interacting with the button.
To enhance accessibility further, marking non-essential elements like an svg
with aria-hidden="true"
can help streamline the user experience.
Here is a sample code snippet showcasing how to create an accessible button with an SVG or IMG element.
update: If using an img
tag, setting alt=""
can also enhance accessibility, as suggested by slugolicious.
const btn = document.querySelector('.image_button');
const frm = document.querySelector('.form');
btn.addEventListener('click', () => frm.remove());
.image_button {
padding: 3px;
background: none;
border: none;
}
.image_button svg {
width: 1em;
height: 1em;
display: block;
}
.form {
border: 1px solid black;
padding: 1em;
}
<div class="form">
<p>The close button below can be closed via keyboard, and should also be screen reader friendly. For keyboard users, press TAB to highlight and SPACE to close.</p>
Close me ->
<button aria-label="close" class="image_button">
<svg
aria-hidden="true"
viewPort="0 0 12 12" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<line x1="0" y1="12" x2="12" y2="0"
stroke="red" stroke-width="2"/>
<line x1="0" y1="0" x2="12" y2="12"
stroke="red" stroke-width="2"/>
</svg>
</button>
</div>