0

I have a problem with my jQuery, I have a website with multiple anchors and I use a smooth scrolling to go to the anchors. The probleme is that I have the anchor in the URL.

Here's my code :

/**
 * Checks if anchor exists. If it exists, scroll to it
 */
function scroll_if_anchor(href) {
    href = typeof(href) == "string" ? href : $(this).attr("href");

    // dynamically caluclates height
    var fromTop;
    var speed = 750; // Durée de l'animation (en ms)
    var headerHeight = $('#header').height(),
        navHeight = $('.nav-secondaire').height();

    if( headerHeight + navHeight > 200){
        fromTop = 300;
    } else {
        fromTop = 120;
    }

    // If our Href points to a valid, non-empty anchor, and is on the same page (e.g. #foo)
    // Legacy jQuery and IE7 may have issues: http://stackoverflow.com/q/1593174
    if(href.indexOf("#") == 0) {
        var $target = $(href);

        // Older browser without pushState might flicker here, as they momentarily
        // jump to the wrong position (IE < 10)
        if($target.length) {
            $('html, body').animate({ scrollTop: $target.offset().top - fromTop }, speed);
            if(history && "pushState" in history) {
                history.pushState({}, document.title, window.location.pathname + href);
                return false;
            }
        }
    }
}    

// When page loads, scroll to anchors
scroll_if_anchor(window.location.hash);

// Intercept all clicks on anchors
$("body").on("click", "a", scroll_if_anchor); 

Do you have an idea ?

Thank you so much !

vcapra1
  • 1,988
  • 3
  • 26
  • 45

4 Answers4

0

Code you've posted enables smooth scrolling for links on the page, to scroll to specific anchor when you visit page add following code to the end of your javascript. Make sure to call it when full page is loaded.

var url = window.location.hash;
url = url.substring(url.indexOf('#'));
scroll_if_anchor(url)
Alex Ponomarev
  • 885
  • 5
  • 11
0

The location.hash may not include the initial pound sign, so you have to make sure it's present before passing it to your function (which expects the pound sign to be there):

scroll_if_anchor(location.hash.replace(/^([^#])/, '#$1'));
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
0

Adding this answer might help a few landing on this page.

// first: get the full url

var hash_url = window.location.href;

// second: simply do a split on the hash

hash_url = hash_url.split('#'); var clean_url = hash_url[0];

// Check your clean url alert(clean_url);

// then:

  1. you can do a fresh refresh of the page with a new hashtag.
  2. for in-page scrolling: add it to 'clean_url' and use scrollTop().

window.location.replace(clean_url+"#your_new_hash");

KJS
  • 1,176
  • 1
  • 13
  • 29
-1

In this Question:

How to remove the hash from window.location (URL) with JavaScript without page refresh?

you can use the follow code remove hash

history.replaceState(null, null, ' ');

我零0七
  • 315
  • 3
  • 6