calo
calo

Reputation: 141

Show on hover, hide on click with jQuery

I've been trying some basic move in jQuery but I'm a beginner in it. How do achieve that?

Here is my code so far :

jQuery(document).ready(function () {

    // show/hide
    jQuery('#div').hide(); //hide at the beginning

    jQuery('#hover').hover(function () {
        jQuery("#div").show(400);
        jQuery('#hover').text('-');
        jQuery('#hover').addClass('click');
        jQuery('.click').height('auto');
        jQuery('.click').width('auto');
        jQuery('.click').css("font-size", "1em");
    }), jQuery("#div").hover(function () {
        //nothing on hover over
    }, function () {
        //hide on hover out
    });
});

My HTML markup is the following :

<a id="hover" href="javascript:;">Hide</a>
<div id="div">test</div>

I got the feeling I'm in the wrong way to do it. Can you help me?

Upvotes: 1

Views: 4055

Answers (2)

Smern
Smern

Reputation: 19066

I think I figured out what you are going for. I modified your dom and used classes to make it more flexible as this looks like something you might have multiple of, if not you can switch back to id's.

fiddle

jQuery(document).ready(function () {
    jQuery(".div").hide(); //hide at the beginning

    jQuery('.hover').hover(function () {
        jQuery(this).siblings(".div").show(400);
    });
    jQuery(".div").on("mouseout", function () {
        jQuery(this).hide();
    });
});

Here is another option using a click on a text that changes (open/close):

fiddle

jQuery(document).ready(function () {
    jQuery(".div").hide(); //hide at the beginning

    function hideDiv(e) {
        e.preventDefault();
        jQuery(this).text('open')
            .click(showDiv)
            .siblings(".div").hide(400)
    }

    function showDiv(e) {
        e.preventDefault();
        jQuery(this).text('close')
            .click(hideDiv)
            .siblings(".div").show(400)
    }
    jQuery('.hover').click(showDiv);
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

Your syntax seems a little off, as you've declared two hover functions and don't even have a click handler?

Try this:

$('#hover')
    .mouseenter(function() {
        $('#div').show();
    })
    .click(function(e) {
        e.preventDefault();
        $('#div').hide();
    }); 

Example fiddle

Upvotes: 3

Related Questions