Search code examples
jqueryrefreshreload

How do I simulate a click only on page refreshes?


I want to simulate a click,

$("#genStats").trigger("click");

every time I refresh the page

window.location.reload()

but not on the initial page load.

What's the easiest way of doing this?


Solution

  • Check out this other SO post: Check if page gets reloaded or refreshed in Javascript

    The catch here is that this detects if it is the first time the user has landed on the page. So if they land there and refresh, you will get the desired effect. If they leave and come back, however, it will treat it the same as a refresh. If this is unacceptable, you will need to have a script on all of your other pages that clears this cookie.

    Here's what you would do in your case:

    function isFirstVisit() {
        if (document.cookie.indexOf('beenhere') === -1) {
            // cookie doesn't exist, create it now
            document.cookie = 'beenhere=1';
            return true;
        }
        return false;
    }
    
    $(document).ready(function(){
        if (!isFirstVisit()) {
            $("#genStats").trigger("click");
        }
    });
    

    And to remove the cookie on your other pages:

    function removeCookie(sKey) {  
        if (!sKey || !this.hasItem(sKey)) { return; }  
        var oExpDate = new Date();  
        oExpDate.setDate(oExpDate.getDate() - 1);  
        document.cookie = escape(sKey) + "=; expires=" + oExpDate.toGMTString() + "; path=/";  
    }
    removeCookie("beenhere");
    

    Here's a good resource on document.cookie