Fix - window.location.href is not a function Error in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Burst

Fix - window.location.href is not a function Error #

The "window.location.href is not a function error" occurs when we try to invoke the href property on the window.location object. To solve the error, use the assign method on the window.location property, e.g. window.location.assign('https://google.com').

window location href is not a function

Here is an example of how the error occurs.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <button id="btn">Change location</button> <!-- โœ… Your JS script here โœ… --> <script src="index.js"></script> </body> </html>

And this is the code in our index.js file.

index.js
const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick() { // โ›”๏ธ TypeError: window.location.href is not a function window.location.href('https://google.com'); });

We tried to invoke the href property as a function, which caused the error, instead you should use the window.location.assign method.

index.js
const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick() { // โœ… works window.location.assign('https://google.com'); });

The window.location.assign method enables us to navigate to a new page.

You could achieve the same result if you assign a string to the window.location.href property.

index.js
btn.addEventListener('click', function onClick() { // โœ… works window.location.href = 'https://google.com'; });

If you load the page and click on the button, you will navigate to the webpage you assigned to the property.

If you need to check out all of the properties on the location object, here is a link from the MDN docs.

Similar methods to assign include:

  • window.location.reload() - reloads the current URL, like the refresh button.
  • window.location.replace() - redirects to the provided URL. The difference from the assign() method is that when using the replace() method, the current page is not saved in session history, so users are not able to use the back button to navigate to it.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee