0

I have this javascript to offset a fixed header in a page with anchorlinks (only when the page loads with an anchor-link):

(function() {
        if (document.location.hash) {
            setTimeout(function() {
                window.scrollTo(window.scrollX, window.scrollY - 100);
            }, 10);
        }
    })();

The problem is that this only works in chrome. In firefox the first anchor link works perfectly fine but the 2nd, 3rd etc are off (2nd 200xp, 3rd 300px etc.). It doesn't do anything at all in IE11. Is there a way to do this in pure jquery for better browser compatibility? Or why is firefox and IE off and chrome works?

ramsys2k
  • 33
  • 7
  • The offset should only happen on pageload with anchor links. Not on normal scroll. This is important as I also use a parallax scroller. – ramsys2k Sep 23 '14 at 12:25

3 Answers3

0

Try listening for the onscroll event, and running then.

$(window).scroll(function(){
    $(window).scrollTop($(window).scrollTop() - 100);
});
Scimonster
  • 32,893
  • 9
  • 77
  • 89
0

Below is a handy jQuery function i use to stroll to any element, also a jsfiddle

$(".js-scrollto").click(function() {
    $('html, body').animate({
        scrollTop: $($(this).attr('href')).offset().top
    }, 2000);
    return false;
});
devools
  • 73
  • 6
0

I found the answer here: offsetting an html anchor to adjust for fixed header

/**
* Check an href for an anchor. If exists, and in document, scroll to it.
* If href argument omitted, assumes context (this) is HTML Element,
* which will be the case when invoked by jQuery after an event
*/
function scroll_if_anchor(href) {
href = typeof(href) == "string" ? href : $(this).attr("href");

// If href missing, ignore
if(!href) return;

// You could easily calculate this dynamically if you prefer
var fromTop = 50;

// If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
// Legacy jQuery and IE7 may have issues: https://stackoverflow.com/q/1593174
if(href.charAt(0) == "#") {
    var $target = $(href);

    // Older browsers without pushState might flicker here, as they momentarily
    // jump to the wrong position (IE < 10)
    if($target.length) {
        $('html, body').animate({ scrollTop: $target.offset().top - fromTop });
        if(history && "pushState" in history) {
            history.pushState({}, document.title, window.location.pathname + href);
            return false;
        }
    }
}
}    

// When our page loads, check to see if it contains and anchor
scroll_if_anchor(window.location.hash);

// Intercept all anchor clicks
$("body").on("click", "a", scroll_if_anchor);

by https://stackoverflow.com/users/1773904/ian-clark

Community
  • 1
  • 1
ramsys2k
  • 33
  • 7