I am trying to make an scroll animation when someone access to an anchor link, like this:
www.miweb.com/section/#anchorLink
And I am doing it with this code, but there’s something wrong in it because i can not execute anything else after it (alert(“the end”) in this case) in case a user access to the URL with no anchor ID.
$('html, body').animate({
scrollTop:$('[name="'+window.location.hash.replace("#", "")+'"]').offset().top
}, 500);
alert("the end");
If the user access from a URL with anchor ID, it will be executed.
How can i do to execute code after this function in any case?
Thanks.
If what you want is to execute code after the animation, do like this:
Update:
After OP’s comments, I think you are having javascript error accessing top property when offset() is null (which is the case when there’s no anchor), so you guard against accesing that possible null reference, like so:
Now the
alert()should print just fine.You could easily spot similar errors like this in future if you look at the browser javascript console, I just did so and saw the error about the null reference.