gbam
gbam

Reputation: 1484

Javascript window.location.href - Refreshes page instead of redirecting

I'm using window.location.href to redirect my browser and I am not sure why one works and one doesn't. When I use a relative link, it refreshes the current page. When I use the full url it redirects. The page I'm on and the Process.aspx page are on the same directory level. So I should just be able to have a relative link? When I do that though it just reloads the current page I'm on. What basic idea am I missing about window.location.href?

    $(document).ready(function() {

    $( "button" )
        .button();
    $("#cancel")
        .click(function( event ) {
            alert("click");

            //Below Line Doesn't work
            window.location.href = "/Process.aspx";

            //Below Line Does work
            window.location.href = "http://localhost:65215/Process.aspx";
    });
});

Upvotes: 4

Views: 38191

Answers (5)

Miqi180
Miqi180

Reputation: 1691

Somewhat of an edge case, but this problem can also occur if you add event listeners to container divs with anchor tags in them and you want to make each container div, rather than just the anchor tag, clickable and then redirect to the link contained within the anchor tag's href attribute. In this case, you want to include event.preventDefault() to prevent this behavior.

Vanilla JS

document.getElementById("myAnchorDiv").addEventListener("click", function(event){
   event.preventDefault();

    //get url 
    URL = ...

   //Below Line should now work
   window.location.href = URL;
});

jQuery

$("#myAnchorDiv").on("click", function( event ) {
    event.preventDefault();

    //get url 
    URL = ...

    //Below Line should now work
    window.location.href = URL;

 });

If you want, you can of course combine the last two lines of code into just one line of code, i.e. something like window.location.href = [your URL];

Upvotes: 2

GANI
GANI

Reputation: 2059

Try this:

window.location = window.location.protocol + 
                  '//' +
                  window.location.hostname +
                  window.location.pathname;

Upvotes: 0

serginhofogo
serginhofogo

Reputation: 43

you can try a hack that only refresh the page, you can implement onclick="location.href='wherever'" and a second href="/Process.aspx" onclick will be fired first and href will take you back.

Upvotes: 0

Splendiferous
Splendiferous

Reputation: 763

Try: location.href = location.origin + "/Process.aspx";

Upvotes: 1

rink.attendant.6
rink.attendant.6

Reputation: 46317

From the Mozilla Developer Network documentation, href is the entire URL of the page. The only relative property in that list is path, which is relative to the host or the domain of the page.

You may also want to look at using the reload or replace method. See How to redirect to another webpage in JavaScript/jQuery?

Upvotes: 7

Related Questions