Emelie
Emelie

Reputation: 31

How can I keep the #-part of the url on load() with jQuery?

I load an html into a div called right-body using jQuery:

$("#right-body").load( "views/" + $(this).attr("page")+ ".html");

This reloads the whole page. Consequently, I lose the hash of the url. How can I keep the hash?

I've tried resetting it after the reload by:

var hash = window.location.hash;
$("#right-body").load( "views/" + $(this).attr("page")+ ".html");
window.location.hash = hash;

but it doesn't work. window.location.hash = hash; seems to be ineffective.

Thank you!

Upvotes: 0

Views: 85

Answers (3)

AndyNope
AndyNope

Reputation: 429

Try this:

if(typeof page === "undefined"){
    var page = "";
}
if(page !== ""){
    page = "views/" + $(this).attr("page")+ ".html";
}

$("#right-body").load(page);

Notice! I do not recommend to use an id then, because it would repeat it again and again. So you need to change the id for your "child"-page. Tell me if it doesn't work!

Upvotes: 0

Dan Shaw
Dan Shaw

Reputation: 21

If the page is reloading after executing .load(), your value for the hash will be reset to undefined.

Rather than storing it in a variable, you could potentially use local or session storage and retrieve the hash once the page has reloaded.

Upvotes: 1

Emelie
Emelie

Reputation: 31

Solved it by putting window.location.hash = hash; as a callback. . Might not be the best solution however as you can see the url flash from "#" to "#myhashparams"...

$("#right-body").load( "views/" + $(this).attr("page")+ ".html", () => {
window.location.hash = hash;
});

Upvotes: 0

Related Questions