Smooth scrolling anchor links and hash url's - also base tag fix

This solution is also very usefull on pages with -Tag. Sometimes the basetag will make anchor links not working properly anymore (redirecting to the base url).

$(document).ready(function () {
  // Anchor links on click based on Chris Coyier's solution: https://css-tricks.com/snippets/jquery/smooth-scrolling/
  $('a[href^="#"]:not([href="#"])').click(function(e) {
    if (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 - 80 + 'px'
        }, 1000);
        return false;
      }
    }
  });

});

// Smooth scrolling anchor links
// to top right away
if (window.location.hash)
  scroll(0, 0);
// void some browsers issue
setTimeout(function () {
  scroll(0, 0);
}, 1);

$(function () {
  // *only* if we have anchor on the url
  $( window ).load(function() {
    if (window.location.hash && $(window.location.hash).length > 0) {
      // smooth scroll to the anchor id
      $('html,body').animate({
        scrollTop: $(window.location.hash).offset().top - 80 + 'px'
      }, 1000, 'swing');
    }
  });

});

Kommentare

Neuen Kommentar schreiben

Plain text

  • Keine HTML-Tags erlaubt.
  • Internet- und E-Mail-Adressen werden automatisch umgewandelt.
  • HTML - Zeilenumbrüche und Absätze werden automatisch erzeugt.
CAPTCHA
Diese Abfrage dient dem Schutz der Seite gegen automatisiertem Spam.