To intercept and handle clicks on links that point to domain.com/#soon, we can use JavaScript to detect such links and show a "Coming Soon" notice instead of allowing the default navigation. This solution uses event delegation to ensure that dynamically added links are also handled, and it leverages the URL API to accurately parse and compare the target URL.
✅ Features of This Solution:
- Event delegation: Listens for clicks on the entire document, ensuring all links are covered—even those added dynamically.
- Accurate URL parsing: Uses the
URL constructor to resolve relative URLs and accurately compare the target domain and hash.
- Simple notice: Displays a non-modal
alert() for simplicity, though this can be replaced with a more modern UI if needed.
📜 JavaScript Code
document.addEventListener('DOMContentLoaded', function () {
document.addEventListener('click', function (e) {
// Check if the clicked element is an anchor tag
if (e.target.matches('a')) {
const link = e.target;
const href = link.getAttribute('href');
// Skip if href is not present
if (!href) return;
try {
// Resolve the full URL using the current page's URL as the base
const url = new URL(href, window.location.href);
// Check if the URL points to domain.com with hash #soon
if (url.hostname === 'domain.com' && url.hash === '#soon') {
e.preventDefault(); // Prevent default navigation
alert('Coming Soon!'); // Show notice
}
} catch (error) {
// Handle invalid URLs gracefully
console.warn('Invalid URL:', href);
}
}
});
});
📌 Notes:
- This script should be included after the DOM is ready, either by placing it at the bottom of the
<body> or wrapping it inside a DOMContentLoaded event listener as shown.
- It only affects links that point to
domain.com/#soon, whether the link is absolute or relative.
- It does not affect external links or links pointing to other hashes on the same domain.
🛠️ Optional Enhancements:
If you'd like to display a custom modal or toast instead of an alert(), you can replace the alert() with something like:
const notice = document.createElement('div');
notice.style.position = 'fixed';
notice.style.top = '20px';
notice.style.left = '50%';
notice.style.transform = 'translateX(-50%)';
notice.style.backgroundColor = '#fff';
notice.style.padding = '10px 20px';
notice.style.borderRadius = '5px';
notice.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)';
notice.style.zIndex = '9999';
notice.textContent = 'Coming Soon!';
document.body.appendChild(notice);
// Remove notice after 3 seconds
setTimeout(() => notice.remove(), 3000);
This would give a smoother, less intrusive experience than a native alert().
✅ Example Use Case:
<a href="#soon">Internal Soon Link</a>
<a href="http://domain.com/#soon">External Soon Link</a>
<a href="http://example.com/#soon">Not Affected</a>
Clicking the first two links will trigger the "Coming Soon!" notice, while the third will proceed normally.
This solution is robust, scalable, and easy to maintain.