Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clickable Div - Wrap anchor link or use JS?

I have a reasonably complex list of Dynamic Div classes which contain various nexted divs to display shop content - the whole thing needs to have a hover state and be clickable (it currently has hover styles applied) and accessible.

I figure I can either approach this by -

1 - Make the containing Div into an Anchor link and style accordingly

2 - Nest an anchor tag within the div class and write a JS function to trigger a click on the anchor when the containing div is clicked.

Whats the thoughts on which is the correct approach?

like image 296
Dancer Avatar asked Dec 12 '25 03:12

Dancer


2 Answers

I would definitely go with the wrapping <a> in that case you don't have to think about setting tabIndex=0, role=link and also you can skip adding the extra JavaScript to make the button clickable and binding the enter key for the same action as well.

Or if the "link" is not taking the user to another location and just show a modal window or some other fancy function you should wrap the <div> with a <button> in that case you can also skip binding the spacebar to the action too, as it is inherited. (But if you really can't do that you should add role=button to the wrapping <a>)

Now you can focus on styling and remember to use both :hover and :focus

like image 106
Daniel Göransson Avatar answered Dec 13 '25 17:12

Daniel Göransson


It's fine to make the <div> clickable by adding an "onclick" handler. However, you should specify an ARIA "role" attribute (such as role="button" or role="link") as well as specify the "tabindex" attribute (tabindex="0") to make it possible to bring the element into focus when using the tab button on the keyboard.

like image 30
Michael Aaron Safyan Avatar answered Dec 13 '25 16:12

Michael Aaron Safyan