Search code examples
javascriptmootools

Show/Hide images alternavely when hover - Mootools


Well I'm trying to get to show the second image only when the mouse is in ( hover or mouseenter or mouseover) the first image using Mootools. Here's the HTML :

<div class="images">
    <img class="first" width="300" src="https://farm8.static.flickr.com/7325/16338493327_1803b63761_b.jpg" alt="First"/>
    <img class="second" width="300" src="https://farm8.static.flickr.com/7383/16336731260_e5d532ea65_b.jpg" alt="Second"/>
</div>

Here's the javascript code:

$$(".images .first").addEvents({
    mouseover: function(){
        $$(".images .second").setStyle('display', 'block');
        $$(".images .second").fade('in');
        this.fade('out');
        this.setStyle('display', 'none');
    },
    mouseleave: function(){
        this.setStyle('display', 'block');
        this.fade('in');
        $$(".images .second").fade('out');
        $$(".images .second").setStyle('display', 'none');
    }
});

I don't know what I did wrong here.Any help with that ? Much appreciated.
here's a jsfiddle if that'll help.


Solution

  • Attaching the events to .images and more explicitly setting the styles seems to help:

    $$(".images").addEvents({
        mouseover: function(){
            $$(".images .second").setStyle('display', 'block');
            $$(".images .second").fade('in');
            $$(".images .first").fade('out');
            $$(".images .first").setStyle('display', 'none');
        },
        mouseleave: function(){
            $$(".images .first").setStyle('display', 'block');
            $$(".images .first").fade('in');
            $$(".images .second").fade('out');
            $$(".images .second").setStyle('display', 'none');
        }
    });
    

    Also, add opacity:0 to .second to have it fade up on the initial mouseenter.

    .second{
        display:none;
        opacity: 0;
    }
    

    https://jsfiddle.net/lemoncurry/6pkpfb3q/1/