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.

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 World</title>
<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.

Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Related Posts

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.