Search code examples
jqueryhtmlcssanchorfixed

Using anchor tags when header element uses fixed position


The header position is fixed and is 100px tall.

There are anchor tags within the header that goto content. The problem is because of the header when its clicked it doesnt scroll to the correct place. i.e. it scrolls to far.

How can I add vertical space (padding) to that anchor position so it shows correctly?

my code

link:

<li>
  <a href="#whoisresponsible">text</a>
</li>

anchor:

<h3>
  <a name="whoisresponsible"></a>Q:&nbsp; Who is responsible for Lifeline’s Suburban Garage Sales?
</h3>

here is a js fiddle

http://jsfiddle.net/lmeyer/XqLRg/3/


Solution

  • jQuery(document).ready(function() {
    
    jQuery(".link").on("click", function(e) {
    
        e.preventDefault();
    
        var name= jQuery(this).attr("href");
        var n=name.split("#"); 
    
        var element = jQuery('[name="'+n[1]+'"]') 
        var container = jQuery("#mainContainer");
    
    
        var number = element.offset().top - container.offset().top + container.scrollTop() -190;
        jQuery(document).scrollTop(number);
    
    
    
    });
    });