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 !