Sam Skirrow
Sam Skirrow

Reputation: 3697

jQuery single page scrolling with links to other pages

I have a site with most of it's content in a single page style with menu links that scroll down the page using the div ID as the anchor (for example www.mydomain.com/#div-id) There are, however, some extra external pages that are also linked in the header.

The issue I'm having is that when I'm on one of the external pages (for example, www.mydomain.com/page-1) the menu links that are used to scroll down the home page don't work (they come out as www.mydomain.com/page-1/#div-id).

jQuery(document).ready(function($){
jQuery('a[href*=#]').click(function (e){
e.preventDefault();
var navHeight = jQuery('.header-site').height();
var id = jQuery(this).attr('rel');
var scrollTo = jQuery('#' + id).offset().top-navHeight;

jQuery('html,body').animate({
    'scrollTop': scrollTo
}, 500);
});

});

I use the link rel attribute to add the div ID so that I don't conflict with other jQuery plugins such as tabs.

Is there a way to solve my issue, so that I can have menu items that scroll to the page, ut when I'm not on the main page, the 'scrollable' menu items link back to the front page (and to the relevant section).

Upvotes: 2

Views: 1095

Answers (2)

BenG
BenG

Reputation: 15154

As they are all on the homepage, change your hrefs to start with /:-

<a href="/#test">test</a>

That will stop this problem - www.mydomain.com/page-1/#div-id

Then split your function out so it can be called on page load and on click, and only preventDefault if you are on the homepage, otherwise let it redirect you to the homepage with the hash.

as all hrefs will now be /# I'm using jQuery('a[href^="/#"]')

function scrollToSection(id) {

  var navHeight = jQuery('.header-site').height();
  var scrollTo = jQuery('#' + id).offset().top - navHeight;

  jQuery('html,body').animate({
    'scrollTop': scrollTo
  }, 500);
}

jQuery(document).ready(function($) {

  var isHomepage = window.location.pathname == '/';

  if (isHomepage && window.location.hash) {
    var id = window.location.hash.split('#')[1];
    scrollToSection(id);
  }

  jQuery('a[href^="/#"]').click(function(e) {

    if (isHomepage) {
      e.preventDefault();
      var id = $(this).attr('href').split('#')[1];
      scrollToSection(id);
    }

  });

});

Upvotes: 1

Abs
Abs

Reputation: 3962

Code snippet to give an idea:

jQuery(document).ready(function($) {

    jQuery('a[href*=#]').click(function(e) {
            //main page found    
            if (document.location.pathname == "/") {
                e.preventDefault();
                var navHeight = jQuery('.header-site').height();
                var id = jQuery(this).attr('rel');
                var scrollTo = jQuery('#' + id).offset().top - navHeight;

                jQuery('html,body').animate({
                    'scrollTop': scrollTo
                }, 500);
            });
    }
});

Upvotes: 0

Related Questions