user626238
user626238

Reputation: 13

Do something if 'div' is display = none or != none

I have a checkbox (checked = false) and a div ( display = none) when

When I click into checkbox, I want to check if div is display ( set checked == true), show "slidingDiv show" and click into checkbox againt - div is display = none ( set checked == false), show "slidingDiv hidden".

function ShowHide() {
            if ($("#slidingDiv").css(":display") == "none") {
                alert("slidingDiv display none.");
            }
            else {
                alert("slidingDiv show.");
            }

            $("#slidingDiv").animate({ "height": "toggle" }, { duration: 400 });
        }

Thank

Upvotes: 1

Views: 14277

Answers (4)

Ioana Zlateva
Ioana Zlateva

Reputation: 51

I think it would be better to use a css class to set the div visible or hidden.

For instance - if you want it to be hidden by default you set

<div id="mydiv" class="mydiv"></div>

where class "mydiv" has display:none; To show it you add class "visible" which has display:block;

if ($("#mydiv").hasClass("visible")) {
  alert('hide');
  $("#mydiv").removeClass('visible');

} else {
  alert('show');      
  $("#mydiv").addClass('visible');
}

Upvotes: 0

BCsongor
BCsongor

Reputation: 869

Look at my working example: http://jsfiddle.net/Briganti/RDq9j/

Have fun :)

Upvotes: 0

kororo
kororo

Reputation: 2012

I think it is better to use this

function showHide()
{
  if($('#mycheckbox').is(':checked'))
  {
    $("#mydiv").show();
  }
  else
  {
    $("#mydiv").hide();
  }
}

Upvotes: 0

Atanas Korchev
Atanas Korchev

Reputation: 30661

You should use this to get the display attribute:

var display = $("#slidingDiv").css("display"); //note that there is no leading colon (':')

Alternatively you can use a simpler check:

if ($("#slidingDiv").is(":visible")) {
  alert("slidingDiv show.");
} else {
  alert("slidingDiv display none.");
}

Upvotes: 2

Related Questions