JQUERY 45
Jump to anchor / go to anchor By micha on 19th November 2024 12:19:56 PM
  1. $('a[href*="#"]').on('click', function(event) {
  2.  
  3.     // Prevent the #hash click action on tabs!!!
  4.     if ($(this).hasClass('ui-tabs-anchor')) {
  5.       event.preventDefault();
  6.     } else {
  7.       event.preventDefault();
  8.       let target = $(this).attr('href');
  9.       let offset = 120;
  10.       jumpToAnchor(target, offset);
  11.     }
  12.   });
  13.  
  14. function jumpToAnchor(target, offset, speed) {
  15.  
  16.   //console.log(jQuery(target));
  17.  
  18.   offset = (typeof offset !== 'undefined') ?  offset : 0;
  19.   speed  = (typeof speed !== 'undefined') ?  speed : 1200;
  20.  
  21.   // Check if the target is a full URL or just a hash
  22.   if (target.startsWith('#')) {
  23.     // It's a hash, scroll to the anchor
  24.     if (jQuery(target).length) {
  25.       jQuery('html, body').stop().animate({
  26.         scrollTop: jQuery(target).offset().top - offset
  27.       }, speed, 'easeInOutExpo');
  28.     }
  29.   } else {
  30.     // It's a full URL, navigate to the link
  31.     window.location.href = target;
  32.   }
  33.  
  34. }

Paste is for source code and general debugging text.

Login or Register to edit, delete and keep track of your pastes and more.

Raw Paste

Login or Register to edit or fork this paste. It's free.