The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →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:
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →#1 Best Overall
- 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
- 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:
$(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.
Best Value
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
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.




