October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Detect Whether a Link or Button Will Redirect with jQuery

Use delegated jQuery events to resolve anchor URLs and classify navigation, while treating buttons, forms, server redirects, and client-side routers as separate cases.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For ordinary links, attach one delegated click handler to the document, resolve the anchor’s href, and compare it with the current URL. Use event.preventDefault() only when you must inspect the destination before navigation. Buttons are different: they have no standard destination, so you must inspect their form and JavaScript handlers.

Detect destinations with one delegated handler

Delegation lets a single listener handle links and buttons that already exist and those added later. The selector limits the listener to elements that can initiate navigation.

$(document).on('click', 'a, button', function (event) {
  const el = event.currentTarget;
  const isAnchor = el.tagName.toLowerCase() === 'a';

  if (!isAnchor) {
    console.log('Button clicked; inspect its form or handlers');
    return;
  }

  const destination = new URL(el.href, window.location.href);
  const current = new URL(window.location.href);

  const classification = {
    url: destination.href,
    differentOrigin: destination.origin !== current.origin,
    differentDocument: destination.href !== current.href
  };

  console.log(classification);
});

An anchor’s href property is resolved to an absolute URL, so relative links such as /account and settings.html can be compared safely. differentOrigin identifies a cross-origin destination; differentDocument also treats a changed path, query string, or fragment as different because it compares the complete resolved URL.

Choose what “different page” means

A hash-only link (for example, #pricing) changes the URL but normally stays in the same document. If your measurement should ignore fragments, compare URLs after clearing hash:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
function isDifferentDocument(anchor) {
  const target = new URL(anchor.href, location.href);
  const current = new URL(location.href);
  target.hash = '';
  current.hash = '';
  return target.href !== current.href;
}

Keep the fragment in the comparison if your application treats in-page state changes as navigation.

Inspect before the browser navigates

Normal anchor navigation is the browser’s default action. Cancel it, perform your inspection, and then continue deliberately when necessary:

Rank #2
Sale
JavaScript and jQuery: Interactive Front-End Web Development
  • JavaScript Jquery
  • Introduces core programming concepts in JavaScript and jQuery
  • Uses clear descriptions, inspiring examples, and easy-to-follow diagrams
$(document).on('click', 'a', function (event) {
  const destination = new URL(this.href, window.location.href);

  event.preventDefault();

  const isExternal = destination.origin !== window.location.origin;
  console.log({ href: destination.href, isExternal });

  // Continue only after inspection or logging has completed.
  window.location.assign(destination.href);
});

Calling preventDefault() cancels the browser’s default action; it does not stop other event handlers or prevent a script from assigning a new location. If code needs to know whether cancellation has occurred, jQuery exposes event.isDefaultPrevented().

Do not cancel every click accidentally

Users can request a new tab or window with modifier keys, and an anchor can specify target="_blank". A production policy should decide whether those actions are logged, cancelled, or left untouched. A conservative example leaves those browser behaviors alone:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
$(document).on('click', 'a', function (event) {
  if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
  if (this.target === '_blank') return;

  const destination = new URL(this.href, location.href);
  // Inspect destination here; call event.preventDefault() only if required.
});

Buttons need a different inspection path

A button has no href. Its navigation may be caused by form submission, an inline event attribute, another jQuery handler, a router, window.location, location.replace(), or asynchronous code. A click listener can identify the button, but it cannot infer the eventual URL from the element alone.

Check form submission

For a submit button, inspect the owning form and any button-specific overrides such as formaction. Intercepting the submit event is usually more reliable than treating the button click as the navigation itself.

$(document).on('submit', 'form', function (event) {
  const form = event.currentTarget;
  const submitter = event.originalEvent && event.originalEvent.submitter;
  const action = (submitter && submitter.getAttribute('formaction')) ||
                 form.getAttribute('action') ||
                 window.location.href;
  const method = (submitter && submitter.getAttribute('formmethod')) ||
                 form.getAttribute('method') || 'get';

  const destination = new URL(action, window.location.href);
  console.log({ action: destination.href, method: method.toLowerCase() });

  // Call event.preventDefault() here only when you will handle the submission.
});

A form using method="post" may submit data to the same URL, while a form can also be redirected by the server after submission. The action URL therefore describes the request target, not necessarily the final page.

Trace script-driven buttons

For buttons that call application code, inspect the registered handler, router configuration, or inline code for assignments such as location.href, location.assign(), and location.replace(). location.replace() navigates without adding the originating page to session history, so it has different back-button behavior from ordinary assignment or location.assign(). If the destination is computed asynchronously, observe the runtime action rather than relying on the click element’s attributes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Compare detection strategies

Navigation mechanism What you can inspect at click time What remains uncertain Useful event
Anchor default navigation Resolved href, origin, path, query, fragment, and target HTTP redirects returned after the request Delegated click
Form submission Form action, method, and submitter overrides Server response redirects and script changes after submission Delegated submit
Script-set location The button and its registered code URLs calculated later or in asynchronous callbacks click plus runtime tracing
Client-side router Route-triggering click and framework-specific route data Router guards, async loaders, and final history updates Router event or application hook

Important edge cases

  • Server redirects: The anchor’s URL is the requested destination. It cannot reveal every HTTP redirect that the server returns after navigation.
  • javascript: URLs: Treat them as executable code, not ordinary page destinations; do not classify them as external pages solely from their string value.
  • Downloads: A link may request a download rather than render a new document. Decide whether downloads count as redirects for your metric.
  • New tabs: target="_blank" changes where navigation occurs, even though the destination URL can still be resolved.
  • Propagation: preventDefault() affects the browser’s default action only. Use propagation controls only when you specifically need to stop other listeners.
  • Dynamic content: A document-level delegated listener continues to cover matching elements inserted after the listener was registered.

A practical classification helper

Centralize the anchor policy so analytics and navigation code use the same definition of “different page.”

function classifyAnchor(anchor) {
  const target = new URL(anchor.href, location.href);
  const current = new URL(location.href);
  const targetWithoutHash = new URL(target.href);
  const currentWithoutHash = new URL(current.href);

  targetWithoutHash.hash = '';
  currentWithoutHash.hash = '';

  return {
    href: target.href,
    external: target.origin !== current.origin,
    differentDocument: targetWithoutHash.href !== currentWithoutHash.href,
    opensNewContext: anchor.target === '_blank',
    isDownload: anchor.hasAttribute('download')
  };
}

$(document).on('click', 'a', function (event) {
  console.log(classifyAnchor(this));
});

This reports the declared client-side destination. It does not promise that the eventual document URL will be identical, because a server, router, or later script can navigate again.

When certainty requires runtime observation

Static inspection is sufficient for classifying ordinary anchor URLs before a click. It is not sufficient for proving the final page in every case. To establish what actually happened, record the navigation request and resulting URL in the browser’s network and navigation tooling, and instrument application router events where available. For buttons, trace the submit or click handler through to its location change, including asynchronous callbacks.

Quick Recap

SaleBestseller No. 1
Web Design with HTML, CSS, JavaScript and jQuery Set
Web Design with HTML, CSS, JavaScript and jQuery Set
Brand: Wiley; Set of 2 Volumes
$35.05
SaleBestseller No. 2
JavaScript and jQuery: Interactive Front-End Web Development
JavaScript and jQuery: Interactive Front-End Web Development
JavaScript Jquery; Introduces core programming concepts in JavaScript and jQuery; Uses clear descriptions, inspiring examples, and easy-to-follow diagrams
$22.80

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.