Ben Jackson
Ben Jackson

Reputation: 1547

How to use .hover and .click on same element

The idea is to move a div downwards slightly when hovered and when clicked to move further down to reveal content. The problem is that when you have clicked the div and it moves down you are no longer hovering on it so it performs the 'close when not hovered function.

$(function () {
    $('.more').hover(function () { //Open on hover 
        $('#pull_down_content').animate({
            'top': '-360px'
        }, 1000);
    }, function () { //Close when not hovered
        $('#pull_down_content').animate({
            'top': '-380px'
        }, 1000);
    });
});
$('.more').click(function () { //Move down when clicked
    $('#pull_down_content').animate({
        'top': '0px'
    }, 1000);
});

Upvotes: 1

Views: 4833

Answers (2)

adeneo
adeneo

Reputation: 318342

The problem is that when you have clicked the div and it moves down you are no longer hovering on it so it performs the 'close when not hovered function.

I'm not sure I get it? You do know that the element with the bound events is not the same as the one that you are animating ?

Anyway, something like this maybe:

$(function() {
    $('.more').on('mouseenter mouseleave click', function(e) {
        if (!$(this).data('clicked')) {
            var Top = e.type==='mouseenter' ? '-360px' : e.type==='click' ? '0px' : '-380px';
            $('#pull_down_content').stop().animate({'top': Top}, 1000);
            if (e.type==='click') $(this).data('clicked', true);
        }else{
            if (e.type==='click') {
                $(this).data('clicked', false);
                $('#pull_down_content').stop().animate({'top': '-380px'}, 1000);
            }
        }
    });
});

FIDDLE

Upvotes: 1

Jon
Jon

Reputation: 437834

Put a class on the element to signify that it has been clicked, and do not close it if it has that class:

$(function() {        
    $('.more').hover(function(){    //Open on hover 
           $('#pull_down_content').animate({'top':'-360px'},1000);
        },    
        function(){   //Close when not hovered
           if (!$('#pull_down_content').hasClass("expanded"))
               $('#pull_down_content').animate({'top':'-380px'},1000);    
        });
    });
    $('.more').click(function(){    //Move down when clicked
        $('#pull_down_content').addClass("expanded").animate({'top':'0px'},1000);
    });

Of course you now need another trigger to determine when exactly to undo the hover animation after the item has been clicked; how to do that exactly depends on the effect you want to achieve.

Upvotes: 3

Related Questions