How do I make an HTML button not reload the page
Stop page reload on button click by setting the button's type
attribute to "button"
or use JavaScript's event.preventDefault()
in the event handler.
Example:
OR
Both these snippets prevent the default form submission hence the page stays put upon button click.
Quick on button types
HTML buttons within forms, if not defined, can behave as a submit
button, which infers the browser to send form data to a server, causing a page reload. To cancel this, specify the type
to button
or utilize event.preventDefault()
in the click event handler.
On it:
<input type='button' onclick='customFunction()'>
<button type='button' onclick='customFunction()'>
Serving it plain
Achieving an interactive button without employing JavaScript or JQuery is simple. Make it explicit type='button'
and it will not submit form data or cause page reload.
Quiet those JS and jQuery gang: Unless necessary, opt for simple HTML than overindulge with JS and jQuery. Lesser moving parts, lesser things breaking.
Special techniques and not-so-special problems
Work out your HTML and JavaScript to simplify, don't complicate. As coder, handle things soberly and look for potential problems:
Using event.preventDefault()
:
- Inline handlers can be tricky as it makes management hard. Keep JS separate.
- Code modularly, it's easier to handle, debug and maintain.
Delegated event handling in jQuery can save a lot, but don't forget:
- The
event.preventDefault()
should be in effect within your delegated event handler function to halt form submission.
Rightly utilizing event handlers
An incorrect or missing call to event.preventDefault()
can run into unexpected page behavior. Wrap your event logic suitably within event listener callbacks:
While applying jQuery, make sure your callbacks return false:
Making it good for everyone
While preventing page reloads, remember the user experience and accessibility. See if those depending on keyboards and assistive technologies can still interact:
The right practices:
- Using
aria-label
can help users of assistive technology with a clear purpose of the button. - The
tabindex
should be set right to keep navigation intuitive and user friendly.
Compatibility and testing
Your solution needs to work on every platform. Span your tests across different browsers and devices. Additionally, manage for potential asynchronous operations or network delays:
Hungry races:
- When your button triggers an Ajax call, handle potential race conditions.
- Debounce or throttle the click events if they trigger resource-heavy operations to prevent multiple submissions.
Was this article helpful?