←back to thread

Just use a button

(gomakethings.com)
284 points moebrowne | 3 comments | | HN request time: 0.702s | source
Show context
pverheggen ◴[] No.45774978[source]
A good addition to this article is that most buttons should have type="button" on them. By default, buttons are type="submit", which if contained inside a form will submit that form.

I'm sure there are some devs who reach for a div because they're unaware of the proper way to disable submit behavior.

replies(4): >>45775148 #>>45775591 #>>45775683 #>>45775964 #
sam_lowry_ ◴[] No.45775964[source]
Indeed this long rant by OP misses the critical info.

A button of default type will do weird things, IIRC it will skip the JS handler onCick, for instance.

replies(1): >>45776547 #
1. efilife ◴[] No.45776547[source]
I don't think it skips the handler behavior on default but can't check now
replies(1): >>45776613 #
2. Shog9 ◴[] No.45776613[source]
It does not. What it does do is submit the form, so if you trigger some fast change to the page or async behavior from the click event, you may never see it because the submission happens and the page reloads (or a different page loads if form action is set to a different URL). If you're relying on event bubbling, the click handler may run after the form is submitted, which is even less likely to do what you intend.

If you aren't expecting this (and don't know how to discover it e.g. by examining browser dev tools, server logs, etc.) then you'll assume the button is broken and... probably try something else.

Even if you do discover it, you may try something that won't quite have the same reliability - at one point it was common to see folks putting preventDefault() or return false in their click handlers to squelch the (correct) behavior, rather than changing the type of button.

replies(1): >>45776780 #
3. sam_lowry_ ◴[] No.45776780[source]
Yes, you are right. Thanks for the lengthy explanation.