I am trying to write a scroll event that stops a few pixels above the target container. I do however, want that to only happen when the window size is less than 800px.
Sort of like an if condition or a media query where the distance from the anchor depends on the window size.
Now this is the code I'm using (found in another thread):
function offsetAnchor() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 120);
}
}
$(window).on("hashchange", function () {
offsetAnchor();
});
// This is here so that when you enter the page with a hash, // it can provide the offset in that case too. Having a timeout // seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(function() {
offsetAnchor();
}, 1);
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 120
}, 1000);
return false;
}
}
});
As it stands with this code the scrolling stops 120px above the anchor. I want this to only happen on window sizes below 800px though. Made some attempts with:
if($(window).width() < 800)
{
window.scrollTo(window.scrollX, window.scrollY - 120);
} else {
window.scrollTo(window.scrollX, window.scrollY - 0);
}
But it does not seem to work.
Any help would be much appreciated.
Aucun commentaire:
Enregistrer un commentaire