Sanjeev K Sanjeev K - 2 months ago 9
CSS Question

How to make slideToggle dynamic in JQuery

I have a page where multiple div and within each div there is a option to click and toggle the information, I am able to create by defining different IDs of

DIV
but I think that can be done somehow dynamically, here is what I have created in JSFiddle

CSS

.boxwrap {
float: left;
width: 200px;
height: 250px;
border: 1px solid #ccc;
margin: 0 5px 0 0;
text-align: center;
box-sizing: border-box;
padding: 10px;
}
.boxwrap_inner {
float: left;
width: 100%;
background: #ddd;
padding: 5px 0;
text-align: center;
}
.noDisplay {
display: none;
}


HTML

<div class="boxwrap">
<a href="javascript:;" id="button1">Go</a>
<div class="boxwrap_inner noDisplay" id="content1">
Content goes here
</div>
</div>
<div class="boxwrap">
<a href="javascript:;" id="button2">Go</a>
<div class="boxwrap_inner noDisplay" id="content2">
Content goes here
</div>
</div>


JQuery

$('#button1').click(function () {
$("#content1").slideToggle(200);
});
$('#button2').click(function () {
$("#content2").slideToggle(200);
});

Answer

Check this:

$('.boxwrap > a').click(function () {
  $(this).next().slideToggle(200);
});
.boxwrap {
    float: left;
    width: 200px;
    height: 250px;
    border: 1px solid #ccc;
    margin: 0 5px 0 0;
    text-align: center;
    box-sizing: border-box;
    padding: 10px;
}
.boxwrap_inner {
    float: left;
    width: 100%;
    background: #ddd;
    padding: 5px 0;
    text-align: center;
}
.noDisplay {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="boxwrap">
    <a href="javascript:;" id="button1">Go</a>
    <div class="boxwrap_inner noDisplay" id="content1">
        Content goes here
    </div>
</div>
<div class="boxwrap">
    <a href="javascript:;" id="button2">Go</a>
    <div class="boxwrap_inner noDisplay" id="content2">
        Content goes here
    </div>
</div>

Comments