Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if one element is hidden with jquery [duplicate]

I want to show and hide one div as below:

$('#Div1').click(function () {
            if ($("#Div2").hidden) {
                $("#Div2").show(500);
            }
            else {
                $("#Div2").hide(1000);
            }

        });

this code does not work.

and i want to hide div2 with clicking on empty sapce of page how can i do that and where is my code is wrong?

like image 748
mohsen Avatar asked Jan 03 '15 12:01

mohsen


People also ask

How check element is hidden or not in jQuery?

Answer: Use the jQuery :visible Selector You can use the jQuery :visible selector to check whether an element is visible in the layout or not. This selector will also select the elements with visibility: hidden; or opacity: 0; , because they preserve space in the layout even they are not visible to the eye.

Which jQuery method is used to hide selected elements?

The hide() is an inbuilt method in jQuery used to hide the selected element. Syntax: $(selector).

Is Div visible jQuery?

You can use .is(':visible') selects all elements that are visible.


1 Answers

hidden is not a property of a jQuery object. Try is(':hidden')

  $('#Div1').click(function () {
        if ($("#Div2").is(':hidden')) {
            $("#Div2").show(500);
        }
        else {
            $("#Div2").hide(1000);
        }

  });

If the timings were the same you could simply use toggle() which does hide or show based on the current visibility.

  $('#Div1').click(function () {
       $("#Div2").stop().toggle(500);
  });

And as @A. Wolff suggests, to allow for multiple clicks, use stop as well to halt any existing animation in progress:

  $('#Div1').click(function () {
        if ($("#Div2").stop().is(':hidden')) {
            $("#Div2").show(500);
        }
        else {
            $("#Div2").hide(1000);
        }
  }); 

Part 2:

To hide the div when you click anywhere else on the page, listen for click on document:

e.g.

 $(document).click(function(){
     $("#Div2").stop().hide(1000);
 });

for this to work properly though, you cannot allow the click on div1 to propagate to document so change the first part to also use stopPropagation() on the first event argument:

  $('#Div1').click(function (e) {
        e.stopPropagation();       // stop click propagating to document click handler
        if ($("#Div2").is(':hidden')) {
            $("#Div2").show(500);
        }
        else {
            $("#Div2").hide(1000);
        }
  });
like image 162
Gone Coding Avatar answered Oct 15 '22 10:10

Gone Coding