Hamed Adil Hamed Adil - 2 months ago 5
CSS Question

JavaScript: How to save the state of your website structure to a link (or hash link)

In my website I have some part when you 'click' on it, It will show a (pop-up) div & grays the rest of the website, However I want to make a link/hashlink for that state.. something like this ( http://www.mywebsite.com/show-pop-up ), So whenever my visitors type the link above in their browser and go, They will come to my website with (the pop-up visible).
I saw this in Trello.com & Behance.com (When you click in a project it will show as pop-up with a new link in the browser).

Note: I need this in 'pure' JavaScript.


There are several ways you can achieve this. One of the following options may work for you.

Option 1: using hashes. Consider the following url: www.mywebsite.com/index.html#popup. You can retrieve the #popup value on startup of your website and act accordingly. See the code sample below.

document.addEventListener("DOMContentLoaded", function(event) { 

    // Website has loaded.
    var hash = location.hash

    // Check if the hash exists and is popup.
    if (hash && hash === 'popup') {
        // Show your popup

Another option would be to use query strings. Consider the following url: www.mywebsite.com?popup=true. First you have to retrieve the query strings, using for example the following function. Afterwards check if the popup querystring has been used.

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));

var popup = getParameterByName('popup');

// Check if we have the popup parameter.
if (popup) {
   // Show popup