This is another minor annoyance I have been noticing alot lately. When linking to a fragment (section) on a separate page, sometimes the browser will not properly scroll to the fragment. The cause is the prematurity of the scrolling action. If the browser were smart (Opera is), it would wait for images to load before scrolling to the fragment. If you have no clue what I am talking about, then let me explain. On the front page of ScottGu's blog, you will see that each blog post has a link to the comments section on the left side of each post title. Most of the times when you click that link, it instantly drops you down to the coments section, and by the time the abundance of screenshots load the comments are not even on the screen anymore.
It's annoying. I don't think it would be a problem if CSS were used to set the dimensions of each image, but not all content management systems are generous enough for that. So, I wrote a javascript solution to fix it. It checks the fragment part of the url (Javascript refers to this as the "hash") and scrolls down to the element, after the page is done loading. The code will not execute in Opera, because as far as I know that is the only browser that correctly scrolls to fragments. All you need to do is save the following Javascript in an external file (*.js) and import it (with <script> tags) into any page that contain sections that you plan on linking to…
function addLoadEvent(func) { var oldLoad = window.onload; if(typeof window.onload == 'function') { window.onload = function() { if(oldLoad) oldLoad(); func(); } } else window.onload = func; } function scrollToFragment() { var frag = window.location.hash; if(frag != null && frag.length > 1) { var elem = document.getElementById(frag.substring(1)); var posY = 0; while(elem != null) { posY += elem.offsetTop; elem = elem.offsetParent; } posY = parseInt(posY, 10); if(posY > 0) window.scrollTo(0, posY); } } if(!window.opera) addLoadEvent(scrollToFragment);
Best regards…
Thanks for this snippet.
Peace:
Derich
Guess What?
There are a few basic guidelines you should be aware of before leaving a comment…
- If you choose to display your email address, it will not be detected by spam bots
- Comments are limited to 3,000 characters; so far you have used none of them
- HTML will be encoded; links and line breaks will be converted automatically
- Comments containing five or more links will be subject to moderation
