JavaScript

How to redirect to another page using JavaScript

December 11, 2021

How to redirect to another page using JavaScript

In this article we will learn how to redirect to another page using JavaScript, without using libs like jQuery, in a simple and effective way.

redirect to another page using JavaScript cover

Hey you programmer, how are you? Let’s learn something new!

In JavaScript we have two native ways to redirect the user

One is similar to clicking a link and the other does not save history, ie: the back button does not return to the last page

So let’s go to the examples:

// like a HTTP redirect
window.location.replace("https://www.horadecodar.com.br");

// like when you click a link
window.location.href = "https://www.horadecodar.com.br";

These are the two possible ways running on  JavaScript, and should be enough.

Remembering that when using replace, the user will be ‘replaced’ on the new page

Missing an important behavior that is the browser’s back arrow, be aware when using this approach

You don’t need jQuery for this

Many programmers make use of it due to the ease of jQuery, which is questionable

They are looking for ways to do this with the library, which is a mistake.

Because you end up losing performance and creating an unnecessary dependency

That’s because there are ways to do it with the native form of the language, which you should choose

Changing  history

We can also go back to the page with JavaScript, which are in the browser history

For that we have two ways too, let’s learn it:

window.history.back()

window.history.go(-1)

Conclusion

In this article we learned how to redirect to another page running on  JavaScript

We use the window.location.replace and window.location.href methods

The second simulates a click on a link tag, while the first is a simulation of an HTTP redirect

We also saw ways to get back in browser history

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x