简体   繁体   中英

Animating divs inside another div onClick and onMouseLeave

Here's what I'm trying to achieve: I have a div (marked in black in image below), which contains 2 other div (marked in red and blue) - one has a single image and is shown and the other has 3 images and it's currently hidden.

在此输入图像描述

When a user clicks the single image its parent div makes a slide up animation and becomes hidden and the second div shows.

在此输入图像描述

When the user leaves the parent div area - it makes the slide down animation and returns to initial state (image 1).

I wrote this code to make the slide up animation:

$(".img_btn_info").click(function(){
    $(this).parent().animate({'margin-top': '-30px'}, 500);
});

It worked just fine. But now I tried to write the code for the second part, when the mouse leaves, and it didn't work as I expected - it animated down the parent div instead of the first one.

$(".img_btn_info").click(function(){
    $(this).parent().animate({'margin-top': '-30px'}, 500, function(){
        $(this).parent().parent().mouseleave(function(){
            $(this).animate({'margin-top': '30px'}, 500);
        });
    });
});

So how can I make this work correctly?

UPDATE

Here's a jsfiddle of the code

try to change this:

$(".img_btn_info").click(function(){
    $(this).parent().animate({'margin-top': '-30px'}, 500, function(){
        $(this).parent().parent().mouseleave(function(){
            $(this).animate({'margin-top': '30px'}, 500);
        });
    });
});

to this:

    $(".img_btn_info").click(function(){
        var $here = $(this).parent();
        $here.animate({'margin-top': '-30px'}, 500, function(){
            $(this).parent().mouseleave(function(){
                $here.animate({'margin-top': '0'}, 500);
            });
         });
     });

DEMO

I would call all the DOM elements directly instead of using .parent().parent(). etc.

Eg something like:

$(".img_btn_info").click(function(){
    $('#second-box').animate({'margin-top': '-30px'}, 500, function(){
        $('#container').mouseleave(function(){
        $('#second-box').animate({'margin-top': '30px'}, 500);
        });
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM