How to make any element a link using onClick


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.

1. Redirect in the same tab

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>

2. Open in a new tab

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>

3. Using a JavaScript function

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).

BONUS

1. Smooth Exit Animation

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>

2. Accidental Click Protection (Double Check)

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>

Leave a Reply

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