Search code examples
jquerypermalinks

Remove slash if URL starts with #


I am using smoothscroll on a wordpress website which works in some browsers but not others, simply because Wordpress keeps putting a trailing slash in the middle of the URL.

If I click an internal link (eg. #gallery) to scroll to siteurl.com#gallery it actually goes to siteurl.com/#gallery and this does not work in some browsers.

However I do not want to add a function that removes the trailing slash altogether as then other pages will not be linked to (eg. siteurl.com/news).

Any suggestions?

Thanks


Solution

  • Changed the code to the following which works in all browsers regardless of any trailing slash:

    // Add smooth scrolling to all links
    jQuery("a").on('click', function(event) {
    
    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();
    
      // Store hash
      var hash = this.hash;
    
      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      jQuery('html, body').animate({
        scrollTop: jQuery(hash).offset().top
      }, 800, function(){
    
        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
    });