Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run ScrollTop with offset of element by ID

Trying to make the browser scroll to a specific ID with an added offset -

$('html, body').animate({scrollTop: $('#contact').offset().top}, 'slow'); 

What I need to do is to set the offset by -100px. How can I accomplish this?

like image 803
Staffan Estberg Avatar asked Mar 08 '12 14:03

Staffan Estberg


2 Answers

No magic involved, just subtract from the offset top of the element

$('html, body').animate({scrollTop: $('#contact').offset().top -100 }, 'slow'); 
like image 196
charlietfl Avatar answered Oct 14 '22 06:10

charlietfl


jQuery(function($) {   $('a[href*="#"]:not([href="#"])').click(function() {       var target = $(this.hash);         $('html,body').stop().animate({           scrollTop: target.offset().top - 120         }, 'linear');      });         if (location.hash){     var id = $(location.hash);     }     $(window).on('load', function() {     if (location.hash){         $('html,body').animate({scrollTop: id.offset().top -120}, 'linear')     };     }); }); 

this worked for me.

like image 40
fariborz asgarpour Avatar answered Oct 14 '22 05:10

fariborz asgarpour