baao baao - 2 months ago 18
jQuery Question

display:none and jquery show/slideDown

When using

display:none
in css:

#example {
display:none;
}


my content isn't showed with this jQuery function:

$('#div1').on('mouseover', function() {
$('#example').slideDown(2000);

});


But when I use inline style argument
style="display:none"
it works.

Can someone explain why?

Answer

The reason behind this is CSS classes will be specifying the display: none; in the first case, but jQuery thinks the element is visible. To handle this, the best way to do is to define a class .hidden, which equates to display: none; and then assign the class to the #example.

.hidden {display: none;}

Then, remove the class hidden from the element and hide it using jQuery on document ready.

$(document).ready(function () {
    $(".hidden").hide().removeClass("hidden");
});

And after this, whatever you do using jQuery, works like charm.


Without CSS Classes

$(document).ready(function () {
  $("#trigger").click(function () {
    $("#theDiv").toggle();
    return false;
  });
});
#theDiv {display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<a href="#" id="trigger">Show / Hide</a>
<div id="theDiv">
  <p>Hello</p>
</div>

Using CSS hidden / jQuery Alternative

$(document).ready(function () {
  $(".hidden").hide().removeClass("hidden");
  $("#trigger").click(function () {
    $("#theDiv").toggle();
    return false;
  });
});
.hidden {display: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<a href="#" id="trigger">Show / Hide</a>
<div id="theDiv" class="hidden">
  <p>Hello</p>
</div>