Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a javascript offset when linking to href's in HTML document?

I am building a website with a fixed place menubar that is 35 px high on top of my page. In that menu I have four items that link to sections down the page. When I click on the links the page jumps to that section, but the 35 px menubar covers the top of the text.

How can I modify this site so that when I jump down to a section it doesn't link me to the exact part of the HTML document, but 35 px higher to take into consideration the static menubar?

I am doing this with href code:

<a href="#links"><li>Links</li></a>
<h1><a name="links">Links</a></h1>

Thanks!

EDIT: Menubar code

<div id="top-floating-bar"> <!-- Menubar -->
<div class="row">
  <div class="column grid_12">
    <div class="fixed-bar-buttons">
      <ul>
        <a href="#top"><li>Home</li></a>
        <a href="#links"><li>Links</li></a>            
        <a href="#resume"><li>Resume</li></a>
        <a href="#social"><li>Social</li></a>
      </ul>
    </div>
  </div>
</div>
</div> <!-- End the Menubar -->
like image 520
tguidon Avatar asked Mar 20 '26 03:03

tguidon


1 Answers

Description

You can use jQuery .offset() and .scrollTop() function

Update after a discussion with tguidon

I don't know how your top-floating-bar css is defined, but i know what you want. The size of the menubar in the fiddle is not right, because i dont know your definition.

Check out the jSFiddle.

Sample

Html

<head>
    <script src="jquery-1.5.1.min.js" type="text/javascript"></script>
    <script type="text/javascript"><
          $(function() {
            $(".goto").click(function() {
              var target = $(this).attr("href")
              target = target.substring(1,target.length);
              $(window).scrollTop($('a[name="'+target+'"]').offset().top - 35); 
              return false; 
            });
        });
    </script> 
</head>

<div id="top-floating-bar"> <!-- Menubar -->
<div class="row">
  <div class="column grid_12">
    <div class="fixed-bar-buttons">
      <ul>
        <a href="#top" class="goto"><li>Home</li></a>
        <a href="#links" class="goto"><li>Links</li></a>  
        <a href="#resume" class="goto"><li>Resume</li></a>
        <a href="#social" class="goto"><li>Social</li></a>
      </ul>
    </div>
  </div>
</div>
</div> <!-- End the Menubar -->

<br><br><br><br><br>
<a name="top"/> Top Section
<br><br><br><br><br><br><br><br>

<a name="links"/> Links Section
<br><br><br><br><br><br><br><br>

<a name="resume"/> Resume Section
<br><br><br><br><br><br><br><br>

<a name="social"/> Social Section
<br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br>

More Information

  • jQuery.scrollTop()
  • jQuery.offset()
like image 157
dknaack Avatar answered Mar 21 '26 20:03

dknaack