UPDATED CODE: IMPROVED jQuery Image Preloader with Rollover Effect (extension independent)
I have been researching Javascript libraries quite a bit lately and have decided on jQuery. Don’t ask me to say why it is better or worse than the other libraries out there. After reading the documentation I just happen to prefer it.
Suprisingly enough, one of the most common things Javascript is used for is navigation rollovers. Swapping an image source using markup attributes such as onmousover and onmouseout is not difficult by any means. We have all done it the “old” way and most of us still do, but there is hope!
I normally use unordered lists for my menus, but for simplicity’s sake, and no need to reference CSS rules, here is an example of a very basic menu.
<div id="navWrapper"> <a href="page1"> <img src="../assets/images/page1.png" /></a> <a href="page2"> <img src="../assets/images/page2.png" /></a> <a href="page3"> <img src="../assets/images/page3.png" /></a> </div>
Now what we would usually do is add “onmouseover” and “onmouseout” events to each anchor (link) and an “id” attribute to each anchor’s child image. Wouldn’t it be great if we didn’t have to clutter the (X)HTML with javascript? There must be a better way… this is the thought that started me on my introduction to jQuery 🙂
Using only the markup above and the Javascript referenced below, we can achive the same result of my previous Javascript image preloader/swapping function post.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" /></script> <script type="text/javascript"> $(document).ready(function() { //preload images var preloadedImages = new Array(); $('#navWrapper img').each(function(i) { preloadedImages[i] = new Image(); preloadedImages[i].src = $(this).attr('src').split('.png').join('-over.png'); }); //rollover effect $('#navWrapper a').hover(function() { $(this).find('img').attr('src', $(this).find('img').attr('src').split('.png').join('-over.png')); }, function() { $(this).find('img').attr('src', $(this).find('img').attr('src').split('-over.png').join('.png')); }); }); </script>
Now we can have an image preloader that requires no arguments and the rollover effect without any additional markup 😀