javascriptexternal-links

External link to a 'page' that is actually a div made visible onclick


I have a simple site that has only a couple pages, including 'stockists' & 'contact'. I thought i was being tricky by making these as divs that are hidden when the main page loads, and are revealed when clicking on the corresponding menu item, using 'onclick="showStockists()" which runs a function that basically just changes the divs' opacity & z-index.

This all works & looks great as it is, but kind of fell through when i realised i don't think i can link to these 'states' externally, ie: sending someone a link to the stockists page. Is there a way to have a link such as mysite.com/stockists that somehow on page load will run the 'showStockists()' function? Or am i dreaming & have done this in a very convoluted way.

If it helps, here's pretty much how i have it (as it is, the function also re-hides the side menu, which itself is hidden on page load & revealed by a hamburger, and hides the contact 'page' if it's visible) :

HTML:

<div class="menuItem" onclick="showStockists(); closeNav();">STOCKISTS</div>

JS:

function showStockists() {
sideMenu.style.visibility = "hidden";
stockists.style.opacity=1;
stockists.style.zIndex=2;
contact.style.opacity=0;
}

Solution

  • You can do this using Query String: mysite.com/?stockists=1

    $( document ).ready(function() {
        var stockists = getParameterByName('stockists');
        if(stockists==1)
           showStockists();
    });
    
    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, " "));
    }