Reputation: 41
I am currently using the below to toggle multiple div's but am wondering if i can combine all of these into one?
<script type="text/javascript">
$(document).ready(function() {
$("#tvehicle").click(function() {
$("#div7").toggle();
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#tvehicle2").click(function() {
$("#vehicle2").toggle();
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#tproperty").click(function() {
$("#div8").toggle();
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#thproperty1").click(function() {
$("#hproperty1").toggle();
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#thproperty2").click(function() {
$("#hproperty2").toggle();
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#thproperty3").click(function() {
$("#hproperty3").toggle();
});
});
</script>
Upvotes: 2
Views: 293
Reputation: 45121
You can use data attributes to specify which element to toggle. example
$(document).ready(function(){
var toggler = function() {
var toToggle = $(this).data().toggleId; //Id of an element to toggle
$("#" + toToggle).toggle();
};
$(".togglers").on("click", ".toggler", toggler);
});
HTML structure
<div class="togglers">
<div class="toggler" data-toggle-id="to-toggle-1">Click to toggle 1</div>
<div class="to-toggle" id="to-toggle-1">I will be toggled #1</div>
<div class="toggler" data-toggle-id="to-toggle-2">Click to toggle 2</div>
<div class="to-toggle" id="to-toggle-2">I will be toggled #2</div>
<div class="toggler" data-toggle-id="to-toggle-3">Click to toggle 3</div>
<div class="to-toggle" id="to-toggle-3">I will be toggled #3</div>
</div>
Upvotes: 0
Reputation: 27311
Add a class to all the divs, e.g.:
<div id="tvehicle2" class="toggleable"> ... </div>
then you can do:
$(".toggleable").click(function () {
$(this).toggle();
});
if you don't want (or can't) add a class to all the toggleable items, you can also combine multiple id-references in a selector:
$('#tvehicle1, #tvehicle2, #tv3').click(function () {
$(this).toggle();
});
Upvotes: 1
Reputation: 231
<script type="text/javascript">
$(document).ready(function(){
$("#tvehicle").click(function(){
$("#div7").toggle();
});
$("#tvehicle2").click(function(){
$("#vehicle2").toggle();
});
//AND SO ON...
});
</script>
You can put all functions in one single document.ready function. Like above :)... Also you dont have to have new <script>
tags for every function.
Upvotes: 1