window.location.href is not a function Error in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 2, 2024
2 min

banner

# window.location.href is not a function Error in JavaScript

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.

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, so the error occurred.

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'); });

using window location assign method

The code for this article is available on GitHub

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 the session history, so users are not able to use the back button to navigate to it.
The code for this article is available on GitHub

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.