News for hackers. Stuff that matters.
Re:Just Use a Button by cferdinandi on Friday October 31, 2025 @01:48PM (#45774711)
Hey, it's me, the original author!

The issue isn't with tabindex=0 specifically, but fucking with tabindex in general. People go down that path, and start putting that shit on everything, like it's Frank's Red Hot.

And in my experience, the same folks who use div's instead of button's are the ones who don't know better and start throwing tabindex around.

"why do you need to listen for events at the document level?"

Not events generally, keydown events specifically, which do not fire on child elements of the document.

Re:Just Use a Button by pverheggen on Friday October 31, 2025 @02:03PM (#45774861)
Not sure about that, MDN's example shows keydown being attached to an element.

https://developer.mozilla.org/en-US/docs/Web/API/Element/key...

Re:Just Use a Button by susam on Friday October 31, 2025 @02:29PM (#45775151)
> Not events generally, keydown events specifically, which do not fire on child elements of the document.

Are you sure? I have a 17 year old HTML tool written using plain, vanilla JavaScript where keydown on a child element seems to have been working as expected.

https://susam.net/quickqwerty.html

https://github.com/susam/quickqwerty/blob/1.2.0/quickqwerty....

Nice article, by the way!

Re:Just Use a Button by skrebbel on Friday October 31, 2025 @02:37PM (#45775223)
I think that’s because it’s an input and not a div, so it can get focus. Im not sure whether tabindex is enough to make a div do that too, article suggests no
Re:Just Use a Button by kyle-rb on Friday October 31, 2025 @05:07PM (#45776706)
Hi, good premise overall, but there are just a lot of little things that are off.

- It only counts as "fucking with tabindex" if you give it a value that's not 0 or -1. You should give that specific disclaimer, because there are uses for tabindex=0 other than reimplementing <button>.

- Divs can definitely receive keydown events. If I go to an arbitrary web page, pick a div and run `div.tabIndex = 0;` + `div.addEventListener('keydown', console.log);`, I see those events coming through when I have the div keyboard-focused.

- "Run your code, somehow..." I think just calling `notRealBtn.click()` is the best option.

- Stupid but semi-interesting nitpick: 'keydown' is good for enter, but you should be listening to 'keyup' for the space bar. That's how real <button>s work anyway.

- The 'keyup' listener should call event.preventDefault() to prevent the default behavior of the space bar scrolling the page.