jquery page load event

maqskywalker
maqskywalker used Ask the Experts™
on
Hi experts,

I'm using jQuery on a html page.
I'm using this version of jQuery  http://code.jquery.com/jquery-1.10.1.js

In my page jquery code I have this code.
This code shows a div called #div1 whenever the page load.

    // after page refresh this fires
    $(window).load(function() {
     //insert all your ajax callback code here.
     //Which will run only after page is fully loaded in background.
                        
                // show div called div 1 on page load
            $("#div1").show();      
    });



On my page i have two divs. One has id="div1" and the other has id="div2".

Is there a way to do this?:

On the very first page load show #div1.

On the 2nd page load or any other page load after the 2nd page load show #div2 and hide #div1
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2017
Distinguished Expert 2018

Commented:
On the 2nd page load
What do you mean by page load? Does this mean a page refresh (F5?)

If so you are resetting state so if you want the behaviour you are describing you need to maintain some sort of state to say what has happened in the past.

My question is if you are going to do this (maintain state) then why not simply have the the server process either render out div1 or div2 depending on the state?

I suspect I am not understanding your requirement entirely - please can you elaborate a bit more.
Freelancer
Top Expert 2010
Commented:
I assume you want this: the first time a page is loaded you want to show div1, all next times you want to hide div1 and show div2. If this is your question you can accomplish this just setting a cookie. First, download jquery.cookie plugin from here: https://github.com/carhartl/jquery-cookie

Then use this code:
    // after page refresh this fires
    $(window).load(function() {
     //insert all your ajax callback code here.
     //Which will run only after page is fully loaded in background.
            var yet_loaded = $.cookie("maqskywalker");
            if (yet_loaded === null)
            {
                // show div called div 1 on page load
                $("#div1").show();      
                $.cookie("maqskywalker", "loaded yet");      
            }
            else
            {
                $("#div1").hide();      
                $("#div2").show();      
            }
    });

Open in new window

Author

Commented:
Thanks.
Marco GasiFreelancer
Top Expert 2010

Commented:
Thanks for points

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial