I am using the following jquery script on my site to scroll down on blog entry pages from a comments link at the top to the actual comments at the bottom:
jQuery(document).ready(function(){
var TopPosition = jQuery('#comments').offset().top;
jQuery('.comments-link').click(function(){
jQuery('html, body').animate({scrollTop:TopPosition}, 2000, 'swing');
return false;
});
});
I’d also like the page to scroll down to “#respond’ when ‘#comments’ does not exist. Is this possible somehow in jquery with an if/else/and?
Also, is it possible to link from a different page with a comments link (i.e. my blog’s index page) to the individual blog entry’s comments and also have the animated scroll down?
Hope that makes sense.
If you want to scroll to
#respondwhen#commentsdoesn’t exist, just check the length of the object returned by the selector… if it is 0 then it’s not on the page, and you can use theoffset().topof#respondinstead.To scroll down on page load, you would need to use a hash (for example
page.php#comments), however traditionally you would have an anchor tag (<a name="comments'></a>), and the page would just jump to it. If you want to have a smooth scroll, you can look atlocation.hashand then trigger the scroll. Since it is effectively the same as theonClickI would break it out into a function that you can call for both: