TimVNL
TimVNL

Reputation: 43

Smooth scroll calling div directly

I am making a one page website with smootscroll using this script

$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top - 125
    }, 1000);
    return false;
  }
}
});

But if I call the div directly using for example ?page_id=6#apps it ignores the

target.offset().top - 125 

how can ik fix this?

Upvotes: 0

Views: 105

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

See if it fits your needs, using onhashchange event:

$(function () {
    $('a[href*=#]:not([href=#])').click(scrollToElement);
});

$(window).one('hashchange', scrollToElement).on('load', function () {
    $(this).triggerHandler('hashchange');
});

function scrollToElement() {
    var hash = this.hash ? this.hash : window.location.hash;
    var $target = $(hash).length ? $(hash) : $('[name=' + hash.slice(1) + ']');
    if ($target.length) {
        $('html,body').animate({
            scrollTop: $target.offset().top - 125
        }, 1000);
        return false;
    }
}

Upvotes: 1

Related Questions