I note the question is tagged WCAG and “accessibility”.
The answer to your question is therefore “don’t do that.” The other answers on this page will all work fine, for everyone except the people who need it to work, i.e. those using screenreaders or other assistive technology. None of the javascript-based solutions here are WCAG compliant.
What you want is a <button>
. That gives you your tabindex and keyboard control for free.
You can also force a <div>
to work like a <button>
by adding ARIA markup (though it’s better and easier to just use the tag that already does what you need it to do.)
If absolutely necessary, a good introduction to using ARIA for pseudo-buttons is here:
https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role
The gist of it is, you need to add the role="button"
attribute, and manage the state of the aria-pressed
attribute manually (by capturing key events and clicks in javascript; other answers have covered this pretty thoroughly so I won’t repeat the details)