pph
pph

Reputation: 11

Scroll Handling with Javascript

I am new to web programming and I stumbled on something strange while working on my website. I use Wordpress but here I had to dive in the Javascript code to get it done.

What I want to achieve is the following: I want people to get to see the header of my website when they arrive but not be bothered by it once they read stuff on my site. What I figured out is that I want the website to scroll down if a) people are at the top of the site and b) if they click on a menu link. When people are already on the site and click on a menu item to change pages, I would like to maintain the scroll position of where they were before.

I tried two versions: This one works like a charm except that the function executes on each reload of the site

var scroll_position = localStorage.getItem('scroll_position');
var header_height = document.getElementById('masthead').offsetHeight;
var menubar_height = document.getElementById('top-bar').offsetHeight;
var page_height = header_height - menubar_height;

jQuery(function () {

    if (window.pageYOffset == scroll_position){
        jQuery(window).scrollTop(page_height);
    }
    else{
       jQuery(window).scrollTop(scroll_position);
    }
});

But as I wanted to execute the function only on clicking one of the menu items, I tried:

jQuery("#top-menu ul li a").click(function(){

    if (window.pageYOffset == scroll_position){
        jQuery(window).scrollTop(page_height);
    }
    else{
        jQuery(window).scrollTop(scroll_position);
    }

});

and suddenly the scroll_position variable doesn't change value as before...

I spend the whole day trying to figure this out and I would appreciate very much if someone out there could tell me what I'm doing wrong! Thanks in advance.

Upvotes: 1

Views: 94

Answers (1)

DFayet
DFayet

Reputation: 881

According to the code you gave us, try this

jQuery(function () {
    var header_height = document.getElementById('masthead').offsetHeight;
    var menubar_height = document.getElementById('top-bar').offsetHeight;
    var page_height = header_height - menubar_height;

    jQuery("#top-menu ul li a").click(function(e){
        e.preventDefault();

        var scroll_position = localStorage.getItem('scroll_position');

        if (window.pageYOffset == scroll_position){
            jQuery(window).scrollTop(page_height);
        }
        else{
            jQuery(window).scrollTop(scroll_position);
        }
    });
});

I'm assumig that header_height, menubar_height and page_height can't get altered once the page is loaded, thats why we init them on the page load, not on the click.

Hope it's gonna help you

Upvotes: 1

Related Questions