Wednesday, June 03, 2009

Preload Images with JQuery

So I've been playing with JQuery for I don't remember how long and every time I revisit it, I think it's awesome all over again.

Anyhow, I thought I'd share a couple of scripts that I wrote that are pretty useful. The first one is a image preloader script that I wrote for my wife's photography site. I used the jQuery fade effect to display a set of images, but she wasn't happy because it would start fading even though the load wasn't complete. So in order to please my wife, I did a little research and found some sample scripts that ended up inspiring my script. I posted this script on the inspiration site as well after I did it back in January. So here we go...

    $(document).ready(function() {
vCycleImages = setInterval(
function() {
var bImgLoaded = true;
var images = $("#slideshow img");
for (var i = 0; i < images.length; i++) {
var img = images[i];
if (img.complete == false)
bImgLoaded =
false;
}
if (bImgLoaded) {
$(
"#slideshow").cycle({ delay: 1000, speed: 1000 });
clearInterval(vCycleImages);
}
},
1000);
});

So the way this script works is it sets an interval checking whether or not the images in the #slideshow1 div have completed and flags a bool on way or the other. Then the script checks if the flag is true. If so, then I start the cycle and clear the internal. Pretty simple stuff. The other sample script I have is for resizing a textbox horizontally while typing in it. So here we go again...

    $(document).ready(function() {
$(
".rtb").keypress(function() {
$(
this).width((this.value.length * 9));
this.value = this.value;
});
});

This script works by getting all the textboxes with a class of rtb and then setting the width to the length * 9 on each key stroke. The reason I set the value = value is so that the text starts over and you can see where you started.


Well, that's all I have for now. I'm planning on posting some test cases in my next entry. I've been spending most of my time lately trying to improve my management skills, so my play time with coding has been limited the past couple weeks. Til next time...


As always, please leave your comments if you like or hate the post. Thanks!

kick it on DotNetKicks.com

Related Posts Plugin for WordPress, Blogger...