How to add jQuery fadeIn and fadeOut to mouse event functions?

105 views Asked by At

I am using jQuery to change images on a mouse events (hover), but I can't figure out the best way to add a fadeIn and fadeOut to fire for the following function.

        var sourceIn = function () {
            var $this = $(this);
            var newSource = $this.data('alt-src');
            $this.data('alt-src', $this.attr('src'));
            $this.attr('src', newSource);
        }
        var sourceOut = function () {
            var $this = $(this);
            var newSource = $this.data('alt-src');
            $this.data('alt-src', $this.attr('src'));
            $this.attr('src', newSource);
        }

        $(function () {
            $('img.toggle').mouseenter(sourceIn);
            $('img.toggle').mouseleave(sourceOut);
        });

I have tried numerous ways to append fadeToggle to the above and I'm not sure what the best technique is.

jsFiddle example: http://jsfiddle.net/hn5w7/

1

There are 1 answers

0
tymeJV On BEST ANSWER

Rather than just change the src, use the callback from fadeOut and fadeIn

$this.fadeOut(function() {
    $this.attr('src', newSource).fadeIn();
});

Demo: http://jsfiddle.net/hn5w7/1/