April 20, 2012

Page reload doesn't reset jQuery / CSS styles

Question by Emerson

I’m designing an HTML page which has one button. The user clicks the button and a simple jQuery script animates that div away, revealing lower page content. You can see it here.

I’ve noticed that it looks/works fine the first time, but if I refresh the page with the browser button, it doesn’t fully reset. The initial container is only half on the page. If I enter the URL again and load the page, it resets as expected.
NOTE: This only happens if you scroll down a bit after clicking the initial button… which seems weird.

I had no idea that there was any difference between these two operations, but there clearly is. What is the difference and how can I fix this problem from happening?

Here’s my jQuery code, in case it’s relevant:

    $(document).ready(function(){

    var faqs = $("#FAQ");
    $("#learnmore").click(
        function(){
            $("#home").animate({top:'-=1066px'},600);
            $("#more").animate({top:'-=1066px'}, 600, function() {$("#background").hide();} );
            $("body").css('overflow-y', 'scroll');

            //$("#home").slideUp();
            console.log("jquery loaded");
            }
        );

});

Answer by happyproff

It happens because browser trying to scroll to the same position, what was before page reload. To check it, try press button and don’t scroll to bottom of page and then reload page.
Okey, the reason is clear.

Now we need solution. Try this:

#more {display:none}

in your css. And then use

$("#more").show().animate(...

in your $("#learnmore").click() function. I hope this will solve the problem.

Answer by Starx

It happens because it is cached by the browser.

If you styles are regularly modiefied, then as easy fix is to attach a unique id on the end of the reference, like

<link href="style.css?time=168768234928" ..../>

What it does, it makes the browser think it is a new request everytime it loads.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!