Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two functions to hide element

Tags:

jquery

I have the following three functions:

$(".redDiv").hover(function() {
   $(".blueDiv").show();
}, function() {
    $(".blueDiv").hide();
});
$(".blueDiv").hover(function() {
    $(this).show();
}, function() {
    $(this).hide();
});

$(document).click(function(e) {
    if (!$(".ignoreClick").is(e.target)) {
        $("div").hide();
    }
});

Quite simple, when a mouse hovers over .redDiv or .blueDiv it is shown. Also if a user clicks anywhere in the document -- all divs suppose to be hidden. the only exception for this click if a clicked element has an .ignoreClick class in it.

I need it to hide blueDiv on click even if the mouse is over it. For some reason that does not work. What am I missing?

like image 859
santa Avatar asked Aug 05 '26 08:08

santa


2 Answers

You can use event.stopPropagation in an event handler for the .ignoreClick elements to stop hiding all the divs on document click (the event will not bubble up to the document element).

Also if you fade-out-in the div elements rather than show/hideing them they will still occupy their spot on the document. If you use show/hide then the element will no longer be in the flow of the page and you won't be able to mouse-over any hidden elements to make them show again. If you change the opacity of the divs instead then you can mouse-over a hidden div and it will show up:

var $redDivs  = $('.redDiv'),
    $blueDivs = $('.blueDiv'),
    $ignore   = $('.ignoreClick');
$redDivs.hover(
      function () {         
        $blueDivs.stop().fadeTo(100, 1);
    },
      function () {
        $blueDivs.stop().fadeTo(100, 0);
      }                     
);    
$blueDivs.hover(
      function () {
        $(this).stop().fadeTo(100, 1);
      },
      function () {
        $(this).stop().fadeTo(100, 0);
      }                     
);

$ignore.bind('click', function (event) {
    event.stopPropagation();
});

$(document).click(function(e) {
    $redDivs.add($blueDivs).add($ignore).stop().fadeTo(100, 0);
});

Here is a demo: http://jsfiddle.net/E5f6N/2/

Notice I cached all the selectors, this will help the code run more efficiently.

Docs for .fadeTo(): http://api.jquery.com/fadeto

like image 187
Jasper Avatar answered Aug 06 '26 21:08

Jasper


You could do this:

$(document).click(function(e) {

    $('body').addClass('allHidden');

    if (!$(".ignoreClick").is(e.target)) {
        $("div").hide();
    }
});
$(".blueDiv").hover(function() {

    if(!$('body').hasClass('allHidden')){
        $(this).show();
    });

}, function() {
    $(this).hide();
});
like image 38
wanovak Avatar answered Aug 06 '26 20:08

wanovak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!