Reputation: 85
I'm trying to link to a div within a page and I'm asking window.scrollTo(0, $(this.hash));
to go to the location where the div is located.
When I console.log it, it is correct but when I use it in window.scrollTo it goes to the top of the page. Why would it not go to the correct location?
$(document).ready(function() {
$('a').on('click', function(e){
e.preventDefault();
// console.log(this.hash);
console.log(e.currentTarget.href.indexOf('#'));
console.log($(this.hash));
console.log(window.pageYOffset);
console.log(window.location.hash);
if(e.currentTarget.href.indexOf('#') != -1){
// console.log(window.location);
window.scrollTo(0, $(this.hash)); //the scrollY should be the hash location
console.log($(this.hash));
}
return false;
});
});
Upvotes: 1
Views: 70
Reputation: 2882
I think you've misunderstood what window.scrollTo
does. You can find the documentation here: http://www.w3schools.com/jsref/met_win_scrollto.asp
It basically accepts an xPos and yPos as arguments. Therefore, you could do something like window.scrollTo(0, $(this.hash).offset().top)
or you could do a $(window).animate({scrollTop: $(this.hash).offset().top})
Let me know if that helps!
Upvotes: 1