I’m fairly new to jQuery (1.4.4) but finding it to be an incredible library of tools.
I recently scrapped my old image swapping JavaScripts for some new stuff I wrote for jQuery. It’s all working in jQuery the way it was working before without jQuery. So far so good.
Now I’m fiddling around with adding some jQuery animation effects and find the experience both disappointing and frustrating. I’m hoping it’s just me.
So I have images with an indexed id, like this…
<img id="m-0" src="/normal_0.jpg" />
<img id="m-1" src="/normal_1.jpg" />
etc.
With the following jQuery, I simply swap out the image (“m-0”) on mouseover to an image called “over_0.jpg” by changing the url in “src” for image element id “m-0”.
I’ve greatly simplified the code below for the purposes of this thread. The real code is doing image pre-loading, binding multiple elements, filling an array with all the URL’s for the hover images, etc.
$(document).ready(function() {
var over; var out;
$('img[id|="m"]').each(function (i) {
$(this).hover(over, out);
// *snipped* code in here filling various arrays with URL's
// *snipped* code here doing some image pre-loading
});
function over(event) { // mouseenter
$(this).attr("src", '/over_'+$(this).attr('id').replace(/m-/, "")+'.jpg');
};
function out(event) { // mouseout
$(this).attr("src",'/normal_'+$(this).attr('id').replace(/m-/, "")+'.jpg');
};
});
Ok, so the code above is working for me… swapping images.
The issue or question now is how can I apply a simple fadein or fadeout on the in/out events? I’ve been experimenting today and no matter what I do, I get the image swap and then an animation… or vice versa. It looks ugly since the background shows through… I just want to fade from one image to the next instead of a quick snap from one to the other.
Most of the plugins I’ve found seem to be overkill for this. Or they require two separate image elements… I just want to do it each image with my single img element.
If I can’t do it with a few simple lines, I’m going to live with it.
Thank-you for any suggestions or thoughts.