How to Redirect to Another WebPage Using JavaScript

In this short tip post, we will learn how to perform redirection to another webpage using JavaScript.

Table of Contents

Objective

We need to redirect the user to another webpage on a particular event, say when user clicks on a button.

Approach

We can use window.location.href function of JavaScript to achieve the same.

Code

Here is the code.

<html>
  <head>
<title>Hello Worldtitle>
<script type='text/javascript'>
function redirect() {
  window.location.replace('https://codeforgeek.com')
}
script>
head>
  <body>
    <input type='button' value='clickme' onClick='redirect()'>
  body>
html>

Check out the codepen for the live demo.

See the Pen
redirection
by Shahid Shaikh (@codeforgeek)
on CodePen.


Love JavaScript? Learn more about it here.