Mahtab Mahtab - 4 years ago 96
Javascript Question

Sliding down and up with nested div

I have written codes but they won`t work, please kindly help me!
I have a div with two other div nested into. the first div has h2 tag that should be clicked in order to show the the content of the second div, then click again to hide the content.
here I have my codes, please debug it and help me move forward.



$(document).ready(function() {
$("#toggle").click(function(){

if ($(this).is(":visible")){
$(".item-body").slidDown("normal");
} else {
$(".item-body").slideUp("normal");
}
});
});

.my-item{
width:250px;
heigth:180px;
margin:10px;
padding:20px;
background:green;
border:2px solid black;
}
.item-header{
width:150px;
heigth:120px;
margin:5px;
padding:10px;
background:yellow;
border:1px solid black;
}
.item-body{
width:70px;
heigth:50px;
margin:3px;
padding:5px;
background:purple;
border:1px solid black;
}

<!DOCTYPE HTML>
<html>
<head>
<meta charset = "UTF-8">
<title>Simple Demo</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<div class="my-item">
<div class="item-header">
<h2 id="toggle">Click Me!</h2>
<div class="item-body">My Text!
</div>
</div>
</div>
</body>
</html>




Answer Source

Try setting your first if statement to the following:

if ($(".item-body").is(":visible")) {

Instead of checking if the h1 is visible (which it always will be), this will solve the issue.

Other notes

  • You have a typo with your slideDown() missing an 'e'.
  • You should switch the slideUp() and the slideDown() so that it slideUp()s when it's visible and it slideDown()s if it is not — see my below example.

See this working JSFiddle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download