scrollTo: The jQuery plug-in and our CSS

Today we will talk about the plug-in for jQuery “scrollTo” and its “hidden” dependence with the loading of our CSS files.

jQuery’s scrollTo

The jQuery plug-in scrollTo (developed by Ariel Flesler) enables us to make our website to scroll (scrolling the vertical bar) to any item on our document we need, this way we can focus the user’s attention in that element each time the page is reloaded (for example, an entry in the left menu on our website), sparing the user from having to do it manually. On the website of the plug-in project you can find all (or almost all) the documentation that is needed to integrate it into your own project. Needless to say that you also have to include the JavaScript framework jQuery in your project in order to be able to use this plug-in. To me, this plug-in was really useful, but I found just a small bug in the documentation…

Interaction between scrollTo and our CSS

The mistake in the documentation I am talking about is that it is not explained anywhere (perhaps Ariel himself is not aware of it …) that in order to make the plug-in works perfectly it is mandatory that all CSS rules of the element you want to apply the scrollTo were loaded on the browser before running the scrollTo function. That is, if we try to run the scrollTo to an element and the CSS rules of this element which the plug-in should be applied to, have not been yet read and interpreted by the client browser, the scroll can not be done, and it does not throw us any errors, so that, to the customer’s eyes the scroll has never even tried to run.

The a priori solution that could come to us is to call the scrollTo function once all DOM elements are loaded in the browser. This would use the following syntax of jQuery:

$(function(){
    $('#element').scrollTo($('#destinationElement'));
});

This could be valid, but has only one drawback: the function $(function…) executes the jQuery scrollTo once our DOM is loaded and ready for use, but it does not mean that all the CSS rules have been applied to the elements “#element” or “#elementoDestino” so the scrollTo could work… or not, it depends on how fast your browser loads and interprets the CSS rules.

The solution

The only solution that we have (while browser developers do not implement the triggering of an event once the CSS rules have been loaded and interpreted) is to use the “load” event of the window object of the browser.

window.load = function(){
                  $('#elemento').scrollTo($('#elementoDestino'));
};

The “load” event is triggered once the entire page has been loaded in the browser, including CSS rules. Maybe, it is not the most elegant solution, but it is the only one that solves our problem.

Anyway, apart this little detail about the documentation, the plug-in scrollTo seems to be a great plug-in that saves us a lot of headaches.

Leave a Reply

Your email address will not be published. Required fields are marked *