megwoo
6/25/2015 - 7:21 PM

jQuery Scroll to Anchor

 if ($(window).width() > 1250) {
	var headerHeight = $('header').height(); // when the header position is fixed
} else {
	var headerHeight = 0;
}

// anchor from same page
$('a').click(function(){
	var hashEle = $(this).attr('href').split('#');
	if (hashEle.length > 1) {
		if (hashEle[1] == 'top') {
			$('body, html').animate({
				scrollTop: 0
			},800);
			return false;
		} else {
			$('body, html').animate({
				scrollTop: $('#'+ hashEle[1]).offset().top - headerHeight
			},800);
			return false;
		}
	};
})

// anchor from different page
hashname = window.location.hash.replace('#', '');
elem = $('#' + hashname);
if(hashname.length > 1) {
	if(hashname == 'top') {
		$('body, html').animate({
			scrollTop: 0
		},500); 
		return false;
	} else {
		$('body, html').animate({
			scrollTop: $(elem).offset().top - headerHeight
		},800);
		return false;
	}
};