239

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.

dsgriffin
  • 66,495
  • 17
  • 137
  • 137
user1990525
  • 3,357
  • 4
  • 16
  • 13
  • 2
    **window.location.replace** instead of **document.location.href**. check here,http://stackoverflow.com/questions/503093/how-can-i-make-a-redirect-page-in-jquery-javascript – dreamweiver Jun 06 '13 at 10:18
  • 1
    You can use the `window.open('URL')` ,have a look at this [window.open](https://stackoverflow.com/a/14352248/2417602) link – vikscool Aug 06 '18 at 05:52

4 Answers4

403
//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";
gunr2171
  • 16,104
  • 25
  • 61
  • 88
Alvaro
  • 40,778
  • 30
  • 164
  • 336
114

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>
Ruslan López
  • 4,433
  • 2
  • 26
  • 37
user2459202
  • 1,151
  • 1
  • 7
  • 2
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(); 
Chris Panayotoff
  • 1,744
  • 21
  • 24
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.

MaximeBernard
  • 1,090
  • 1
  • 19
  • 33