In web development, there are several ways to make an element (such as a button or div) a link using the JavaScript onClick event. The choice of method depends on how the page should open: in the same tab or in a new one.
The simplest and most popular way is to use the window.location.href property. This mimics a regular link click.
<button onclick="window.location.href='https://www.overcod.net';">
Go to
</button>
If you need the link to open in a new window or tab, use the window.open() method.
<button onclick="window.open('https://www.overcod.net', '_blank');">
Open in a new window
</button>
If you need to execute some code before the redirect (e.g., save data or send metrics), it’s better to move the logic into a function.
<div onclick="goToPage()" style="cursor:pointer; border:1px solid #000; padding:10px;">
Click this block
</div>
<script>
function goToPage() {
console.log("Logic before redirect...");
window.location.assign("https://www.overcod.net");
}
</script>
Important Tips:
Add cursor: pointer: If you are making something other than <a> or <button> a link, users won’t realize it’s clickable. Add this style in CSS to change the cursor to a “pointer” on hover.
SEO and Accessibility: Search engine bots don’t always follow links created via onclick. If it’s critical navigation, it’s better to use a standard <a href="..."> tag.
Method .assign() vs .replace():
location.assign("url") — keeps the current page in history (Back button works).
location.replace("url") — removes the current page from history (Back button won’t return the user).
This technique prevents the user from seeing a sudden white screen during navigation. We smoothly fade out the current page content before redirecting the user.
<button onclick="smoothRedirect('https://www.overcod.net')" style="padding: 10px 20px; cursor: pointer;">
Smooth Redirect
</button>
<script>
function smoothRedirect(url) {
document.body.style.transition = "opacity 0.5s ease";
document.body.style.opacity = "0";
setTimeout(() => {
window.location.href = url;
}, 500);
}
</script>
This is crucial for pages with forms, surveys, or personal accounts. If a user accidentally clicks a logout button, the script will ask for confirmation.
<button onclick="safeRedirect('https://www.overcod.net')" style="padding: 10px 20px; color: white; background: red; border: none; cursor: pointer;">
Leave Account
</button>
<script>
function safeRedirect(url) {
const isConfirmed = confirm("Are you sure you want to leave? Unsaved changes will be lost.");
if (isConfirmed) {
window.location.assign(url);
}
}
</script>
Sliding Catalog on the Right with CSS and JavaScript
96
HTML Select: hidden placeholder, highlight, and dynamic urgency indicator
157
How to Detect an AdBlocker on Your Site Using JavaScript
261
Leave a Reply