Skip to content Skip to sidebar Skip to footer

Offsetting A Hash Tag Link To Adjust For Fixed Header When Typing Url In Browser In JS

I wish to create a page that allows hash tags to jump to certain contents of the page. e.g. http://example.com/page1 is a normal page http://example.com/page1#info will jump to the

Solution 1:

The following seems to work. The gotoHash() function is basically the same as your existing code, except it's within a timeout, which makes event.preventDefault() unnecessary. This also solves a problem when the function runs after document ready but before the browser has scrolled to a hash:

location.hash = '#d3';  //used for demonstration purposes only

function gotoHash(id) {
  setTimeout(function() {
    var $target = $(id),
        scrollOffset = 100,
        y = $target.offset().top - scrollOffset;

    if ($target.length) {
      window.scrollTo(0, y);
    }
  });
}

$('a[href^="#"]').on('click', function() {
  gotoHash($(this).attr('href'));
});

$(document).ready(function() {
  gotoHash(location.hash);
});
body {
  font: 12px verdana;
  margin: 100px 0px;
}
header {
  height: 100px;
  background: yellow;
  border: 1px solid gray;
  position: fixed;
  top: 0;
  width: 100%;
}
div {
  height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
  <a href="#d1">div 1</a>
  <br>
  <a href="#d2">div 2</a>
  <br>
  <a href="#d3">div 3</a>
  <br>
  <a href="#d4">div 4</a>
  <br>
</header>
<div id="d1">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</div>
<div id="d2">Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
<div id="d3">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</div>
<div id="d4">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

Post a Comment for "Offsetting A Hash Tag Link To Adjust For Fixed Header When Typing Url In Browser In JS"