1

I'm using anchors on my website with several divs. When my page loads, I have a # at the end of my URL like this:

http://www.website.com/projects#third

I also have a fixed header, with 100px height.

I'm using scrollto plugin.

What I'm trying to do is that when my pages loads it scrolls to the #div of the URL, and with the offset of the header height.

Here is what I tried using jQuery, but it's not working.

$(window).load(function() {

    var hashVal = window.location.hash;
    var headerheight = $("header").height();
    $('body').scrollTo(hashVal, { duration: 'slow', offsetTop: headerheight});

});

Can't figure out what I am doing wrong.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
mmdwc
  • 1,095
  • 6
  • 27
  • 53

2 Answers2

0

Try the following:

$(document).ready(function(){
     $('body').scrollTop($('body').scrollTop() + $("header").height());
});
Roger Barreto
  • 2,004
  • 1
  • 17
  • 21
0

The following jsFiddle works fine: http://jsfiddle.net/gp5kev0k/2/

$(window).load(function(){
  var hashVal = "#scrollto";//cannot test this in jsfiddle
  var headerheight = $("#header").height();
  console.log(hashVal)
  console.log(headerheight)
  $('body').scrollTo(hashVal,{duration:'slow', offsetTop : headerheight});
});

The differences are:
I use a div with id=header, probably you also do that but using $("header").height(); you calculate the height of <header></header> (if you have such an element that is fine though..)

I set hashval to a static string because window.location.hash does not work in jsFiddle. Add some console.log commands to see if those pieces work in your code.

Niki van Stein
  • 10,564
  • 3
  • 29
  • 62
  • yes it works, but i'm wondering if the problems comes from this part of my code "var hashVal = window.location.hash;" ? is it possible to get the window.location.hash before scrolling ? – mmdwc Dec 09 '15 at 14:40
  • Yes it should be possible, but I can not test it with jsFidle.. you can console log the hash to see if that part goes wrong or not. – Niki van Stein Dec 09 '15 at 14:45