Scroll to id script, scrolls window to wrong position if I use sticky menu

630 views Asked by At

I have a web page that inserted "Scroll to id" and "Sticky menu" jQuery scripts for them in it. The problem I have is for first click on menu when I am at the top position of page. Its offset from top is different with offset after other clicks (When I am not at the top). I wrote a sample code. If I could not say my mean, I hope you can find it out in sample.
HTML:

<header>
    <a href="#part1">Part1</a>
    <a href="#part2">Part2</a>
    <a href="#part3">Part3</a>
    <a href="#part4">Part4</a>
    <a href="#part5">Part5</a>
    <a href="#part6">Part6</a>
</header>
<section id="part1" class="parts"><h1>Part 1</h1></section>
<section id="part2" class="parts silver"><h1>Part 2</h1></section>
<section id="part3" class="parts"><h1>Part 3</h1></section>
<section id="part4" class="parts silver"><h1>Part 4</h1></section>
<section id="part5" class="parts"><h1>Part 5</h1></section>
<section id="part6" class="parts silver"><h1>Part 6</h1></section>

CSS:

body { margin: 0 0 0 0 }
.parts{ height: 200px; border: 1px gray solid }
.silver { background : silver }
header { background: yellow; height:50px; line-height: 50px; width:100% }
.sticky { position: fixed; left: 0; top: 0; z-index: 2000; width:100% } 
h1 { text-align:right }

jQuery:

// This section is given from http://stackoverflow.com/questions/5284814/jquery-scroll-to-div
// Scroll to id script
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top - 50
        }, 1000);
        return false;
      }
    }
  });
});

// Sticky menu script
var stickyNavTop = $('header').offset().top; 
var stickyNav = function(){  
    var scrollTop = $(window).scrollTop();             
    if (scrollTop > stickyNavTop) {   
        $('header').addClass('sticky');  
    } else {  
        $('header').removeClass('sticky');   
    }  
};  
stickyNav();  
$(window).scroll(function() {  
    stickyNav();  
});

jsFiddle

Please help me to solve this problem.

1

There are 1 answers

0
miimra On

replace your condition

if (scrollTop > stickyNavTop)

with

if (scrollTop >= stickyNavTop)

to include first part in condition and add margin-top to this part.

#part1 {margin-top:50px}