243

How to go to a URL using jQuery or JavaScript.

<a href="javascript:void(0)"  onclick="javascript:goToURL()">Go To URL</a>

function goToURL(url){
// some code to go to url

}

I don't want to use window.location as I want to invoke this link from a popup.

New link should also open in a popup. I also don't want to use Ajax. Just simulate href in JavaScript.

2

4 Answers 4

410
//As an HTTP redirect (back button will not work )
window.location.replace("http://www.google.com");

//like if you click on a link (it will be saved in the session history, 
//so the back button will work as expected)
window.location.href = "http://www.google.com";
8
  • 6
    any way to do it in a new tab?
    – Deekor
    Commented Jan 17, 2017 at 17:03
  • 3
    What's the difference between window.location.href and location.href Commented Aug 21, 2017 at 23:20
  • 2
    @YahyaUddin There is no difference, window.location is the exact same object the same as location, unless it has been overridden elsewhere of cause.
    – 8176135
    Commented Sep 1, 2017 at 6:14
  • 2
    @YahyaUddin I stick to window.location.href just in case someone-else overrode the location variable elsewhere.
    – 8176135
    Commented Sep 1, 2017 at 23:51
  • 2
    @Deekor, onclick="window.open('google.com')" -> this opens in a new tab. Commented Apr 24, 2018 at 16:03
116

why not using?

location.href='http://www.example.com';

<!DOCTYPE html>
<html>

<head>
  <script>
    function goToURL() {
      location.href = 'http://google.it';

    }
  </script>
</head>

<body>
  <a href="javascript:void(0)" onclick="goToURL(); return false;">Go To URL</a>
</body>

</html>

23

window.location is just what you need. Other thing you can do is to create anchor element and simulate click on it

$("<a href='your url'></a>").click(); 
2
  • Haha.. Interesting, but is there any case that this solution will be used? Commented Feb 23, 2017 at 0:34
  • 6
    Maybe if you like to add target="_blank" Commented Dec 18, 2017 at 13:31
3

Actually, you have to use the anchor # to play with this. If you reverse engineer the Gmail url system, you'll find

https://mail.google.com/mail/u/0/#inbox
https://mail.google.com/mail/u/0/#inbox?compose=new

Everything after # is the part your want to load in your page, then you just have to chose where to load it.

By the way, using document.location by adding a #something won't refresh your page.

Not the answer you're looking for? Browse other questions tagged or ask your own question.