Reading URL fragments on page load

2.4k Views Asked by At

In my web application I have a URL using a fragment like so:

http://example.com#login

My question is: can I use the fragment on page load to open a specific portion of my website? If so, how can I use Javascript or jQuery to read and process the fragment?

Background information: I use Remodal (https://github.com/VodkaBears/Remodal) to add custom modal windows to my website. This plugin automatically appends a fragment to the current URL when a modal window is opened. I would like to be able to open modal windows on page load.

2

There are 2 best solutions below

0
On BEST ANSWER

You can use window.location.hash to read the fragment in the URL on load and the open the related modal.

var fragment = window.location.hash; // = '#login' in your example url
if (fragment) {
    $('a[href="' + fragment + '"]').remodal().open();
}
3
On

Edit: although it is correct that the fragment is not added to the HTTP request, the browser can still access it. See @RoryMcCrossan's answer.

https://blog.httpwatch.com/2011/03/01/6-things-you-should-know-about-fragment-urls/

Paragraph 2 states that URL fragments are not sent in HTTP requests.

Edit2:

My final code:

var fragment = window.location.hash;
if (fragment) {
    var modal = $('[data-remodal-id=' + fragment.slice(1) + ']');
    if (modal.length) modal.remodal().open();
}