Works in Chrome and Safari, but not in FF 43.0.2. Firefox ignores the'scrollTop': $target.offset().top -100
line and scrolls directly to the anchor instead. I'm pretty new to programming, so any improvements on the code structure are also appreciated. Thanks!
$('a[href^="#"]').on('click',function(e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
if ($(window).width() < 769) {
$('html, body').stop().animate({
'scrollTop': $target.offset().top -100
}, 700, 'swing', function () {
window.location.hash = target;
});
// Dropdown Menu Logic
$('#nav-icon').toggleClass('open');
$('#nav-mobile ul').slideToggle();
}
else {
$('html, body').stop().animate({
'scrollTop': $target.offset().top -150
}, 700, 'swing', function () {
window.location.hash = target;
});
// Dropdown Menu Logic
$('#nav-icon').toggleClass('open');
$('#nav-mobile ul').slideToggle();
}
});
The code works fine but when you change the window.location
after the animation is over, Firefox "jumps" to the corresponding anchor. This is actually the desired behavior.
To avoid this artifact, use history.pushState
instead and fallback to location.hash
on unsupported browsers :)
if(history.pushState){
history.pushState(null, null, target);
}else{
location.hash = target;
}
An example: http://codepen.io/victmo/pen/dGNvay
Cheers