Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Scroll to anchor on interior and exterior links

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #45723
    jefflupinski
    Member

    So I’ve found myself in quite the predicament. I’m using the attached code to do a simple scroll to an anchor in jQuery. The scroll to works when I’m on the page and it’s scrolling to the anchor locally, but my problem arrises when I need to get back to the scroll to anchor on another page.

    var scrollWin = function (selector) {
    var bar = jQuery(selector).offset().top;
    bar = bar – 80;
    jQuery(‘html, body’).animate({
    scrollTop: bar
    }, 1000);
    }

    jQuery(‘[href^=#]’).click(function(e) {
    scrollWin (jQuery(this).attr(‘href’));
    return false;
    });

    I had found a code that works from exterior pages when the link changes from “#div” to “/#div” on interior pages, but changing the nav links on interior pages is not an option. Any and all help much appreciated, cheers.

    #139751
    jefflupinski
    Member

    So I ended going with this…

    jQuery(document).ready(function(){
    jQuery(‘a[href*=#]:not([href=#])’).click(function() {
    if (location.pathname.replace(/^//,”) == this.pathname.replace(/^//,”)
    || location.hostname == this.hostname) {

    var target = jQuery(this.hash);
    target = target.length ? target : jQuery(‘[name=’ + this.hash.slice(1) +’]’);
    if (target.length) {
    jQuery(‘html,body’).animate({
    scrollTop: target.offset().top – 80
    }, 1000);
    return false;
    }
    }
    });
    });

    and then for external pages traveling back to the page with the anchor links

    jQuery(window).load(function(){
    function goToByScroll(id){
    jQuery(‘html,body’).animate({scrollTop: jQuery(“#”+id).offset().top – 80},’slow’);
    }
    if(window.location.hash != ”) {
    goToByScroll(window.location.hash.substr(1));
    }
    });

    now if you’re offsetting space for say a sticky nav like myself, the window is going to load at the anchor point and then animate to the desired offset upwards. This isn’t ideally what I was looking for, but this is the closest I could get.

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.