Explain Codes LogoExplain Codes Logo

Access event to call preventdefault from custom function originating from onclick attribute of tag

javascript
event-handling
preventdefault
onclick-attribute
Alex KataevbyAlex Kataev·Nov 12, 2024
TLDR

To overrule the default event inside a custom function that is invoked by an onclick attribute, handover the event as an argument:

<button onclick="preventDefaultOnClick(event)">Click me</button> <!-- I won't do what you think I would! -->
function preventDefaultOnClick(e) { e.preventDefault(); // I'm the boss here! // More superpower code here }

Just pass the event to your function and conveniently call e.preventDefault(). This will prevent the browser's default action.

Event handling and preventDefault

When our goal is to override the default behavior of an HTML element like links or form submissions, we turn to our trusted preventDefault(). However, things can become a bit tricky when working with the onclick attribute.

Power of the event object

Passing the event within a function provides access to preventDefault(), granting you control over the event's progression. This is crucial while managing synchronous and asynchronous operations that rely on specific conditions.

For your "older" friends - IE fallback

Not all browsers are created equal. When dealing with IE, you may need a fallback for versions that don't support preventDefault(). In such cases, call upon event.returnValue = false.

Uncluttered HTML with jQuery

Embrace clean code. Instead of cluttering your HTML with inline event handlers, delegate jQuery to assign event handlers that prevent default actions:

$("button").click(function(e) { // "Click me if you can!" e.preventDefault(); // Cool stuff happens here });

More than just clicks!

Let's go beyond the simple onclick. Advanced event handling implies attaching event listeners to unique classes or identifiers. This enhances HTML readability and promotes an efficient separation of concerns.

Redirecting and bypassing cache

There might be situations where you need to programmatically redirect to a URL or incorporate cache busting on element click. You can use window.location and append a timestamp query:

function navigateWithCacheBust(event) { event.preventDefault(); window.location = "/your-url?" + Math.round(new Date().getTime() / 1000); /* Time travel vibes */ }

Choosing when to use preventDefault()

preventDefault() is your go-to tool when it comes to input validation before form submission, intercepting link navigation for user confirmation, or creating dropdown menus that shouldn't navigate upon click.

Dynamic Content manipulation

Modern web apps are known for their dynamic content loading without page refresh. By using preventDefault(), you ensure that link clicks retain users on the present page while triggering the content loading.

Prioritizing Accessibility

For accessibility standards, ensure all actions and navigation are usable without a mouse. Incorporating preventDefault() within keyboard event handlers is crucial for accessible web designs.

Performance Factors

A question that arises: Does using preventDefault() affect performance? It doesn't cause a bottleneck, rather it boosts the user experience by avoiding unnecessary actions or redirects, thus conserving loading time and server resources.