Sarma
Sarma

Reputation: 53

On click scroll to the top with 100px more

I use one page website and when I click menu button about it scrolls down to the top of some div... But Because I am using fixed header scrolling goes to 0px top and I need like 100px top like padding in body tag but I need to say in function I need to scroll to the top of item after 100px from top of the page. Here is my code:

jQuery(document).ready(function($) {
    $(".scroll").click(function(event){     
        event.preventDefault();
        var x = $(this.hash).offset().top;
        $('html,body').animate({scrollTop:x},2000);
    });
});

Upvotes: 1

Views: 7765

Answers (1)

Inanc Gumus
Inanc Gumus

Reputation: 27889

Just adding 100px to $(this.hash).offset().top will do it if I understand you correctly.

Since, offset is getting data relative to the document.

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document. http://api.jquery.com/offset/

Example:

jQuery(document).ready(function($) {
  $(".scroll").click(function(event) {
    event.preventDefault();
    var x = $(this).offset().top;
    $('html,body').animate({scrollTop: x - 100 }, 2000);
  });
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body style="height: 1000px; padding-top: 100px">

<div class="scroll">click to scroll to me</div>
  
</body>
</html>

Upvotes: 1

Related Questions