user3192937
user3192937

Reputation: 35

Convert click code to hover code

How can I change the following menu code to open/close when the mouse hovers, instead of when it is clicked on?

var w = 0;

$('.slide').children().each(function () {
    w += $(this).outerWidth();
});

$('.outer').width(w + 5);
$('.wrap').width(w);
$('.slide').css('left', w);

$('.open').toggle(function () {
    $('.slide').stop().animate({
        left: 0
    });
    $(this).html('close');
}, function () {
    $('.slide').stop().animate({
        left: w
    });
    $(this).html('open');
});

Please check this Demo

In Fiddle, you can see the animation works on click. I need to make it work on hover. Can you help with this ?

Upvotes: 0

Views: 72

Answers (5)

Exodia
Exodia

Reputation: 11

$('.open').on('mouseenter mouseleave', function(e) {

if(e.type === 'mouseleave') {
    $('.slide').stop().animate({
        left: w
    });
    $(this).html('open');
} else {
    $('.slide').stop().animate({
        left: 0
    });
    $(this).html('close');
}

});

Upvotes: 1

Andrew
Andrew

Reputation: 5340

Try using $('.wrap').hover. If $('.open').hover, you will not able to click the nav items.

Also, you can create another wrapper to just wrap div.outer and a.open only

$('.wrap').hover(function() {

    $('.slide').stop().animate({
        left : 0
    });

    //this is the .wrap right now
    $(this).find('a.open').html('close');

}, function() {

    $('.slide').stop().animate({
        left : w
    });

  //this is the .wrap right now
    $(this).find('a.open').html('open');
});

http://jsfiddle.net/rooseve/42sWB/2/

Upvotes: 1

P R
P R

Reputation: 334

var w = 0;
var isVisible = false;
$('.slide').children().each(function() {
    w += $(this).outerWidth();
});

$('.outer').width(w+5);
$('.wrap').width(w);
$('.slide').css('left', w);

$('.open').on("mouseover", function() {
    if(isVisible == false) {
        $('.slide').stop().animate({
            left: 0
        });
        $(this).html('close');
        isVisible = true;
    }
    else {
        $('.slide').stop().animate({
            left: w
        });
        $(this).html('open');
        isVisible = false;
    }
});

Firstly, when you hover the element - the div will be visible, until you hover the element for the second time.

Demo: http://jsfiddle.net/42sWB/3/

Upvotes: 0

dachi
dachi

Reputation: 1602

Just

$('.open').toggle(function() {
    $('.slide').stop().animate({
        left: 0
    });
    $(this).html('close');
}

in this part just replace toggle with hover

Upvotes: 1

nrsharma
nrsharma

Reputation: 2562

Use .hover() api

Try this

$('.open').hover(function () {

instead of

$('.open').toggle(function () {

Upvotes: 1

Related Questions