DG3
DG3

Reputation: 5298

Issue with jQuery onmouseover browser compatability

I got this example from a previous StackOverflow question Jquery onmouseover image size increase

Here is a link to an example of mouseover: http://jsfiddle.net/simevidas/fwUMx/5/

The above example works in Chrome but not in Firefox or IE.

What could be the reason?

Upvotes: 0

Views: 188

Answers (1)

DarthJDG
DarthJDG

Reputation: 16591

Forcing image load events

Check out my reply on this thread: jQuery - Complete loading animation on each individual image?

As it is mentioned on the jQuery documentation page for the load event, there are some issues with it. On IE, it doesn't always fire the first time and on webkit browsers it doesn't always fire if it's read from the cache.

You're using the load() event to save the images original height to a data attribute, but due to the above it's not always set, so the resizing doesn't work.

The solution is to put the following little piece of code into your ready function, which clears and resets the src attribute on all images (or change it to certain images if you like) to force the firing of the load event.

$('img').each(function(){
    var src = $(this).attr('src');
    $(this).attr('src','#');
    $(this).attr('src',src);
});

Here is your fixed jsfiddle demo: http://jsfiddle.net/fwUMx/86/

Automatically cycle through images

If you want to have the same effect to automatically cycle through images, you just need to write a few extra functions and call them in the animation complete callback. Here is a working demo: http://jsfiddle.net/fwUMx/99/

var images = null;
var animation_speed = 500;
var wait = 1500;

function ZoomIn(element){
    element.animate({
        height: element.data('height') * 1.5
    }, animation_speed, function(){
        // Zoom in animation ended, schedule next image
        setTimeout(function(){
            ZoomOut(element);
        }, wait);
        setTimeout(function(){
            var next = element.next();

            // Comment out the next line if you don't want the animation to restart after last image.
            if(element.index() == images.length - 1) next = images.eq(0);

            ZoomIn(next);
        }, wait);
    });
}

function ZoomOut(element){
    element.animate({
        height: element.data('height') * 1
    }, animation_speed);
}

function StartAnimation(){
    // Make sure images object is set
    if(!images) return;

    ZoomIn(images.eq(0));
}

$(function(){
    images = $('img');

    var cnt = images.length;
    var loaded = 0;

    images.load(function() {
        $(this).data('height', this.height);
        loaded++;

        // Start the animation after all images have loaded
        if(loaded == cnt) StartAnimation();
    });

    // Force image load events
    images.each(function(){
        var src = $(this).attr('src');
        $(this).attr('src','#');
        $(this).attr('src',src);
    });
});

Upvotes: 4

Related Questions