Reputation: 495
I have a checkbox and some <div>
s that show/hides whenever a checkbox is checked. Now it all works great but it could be more efficient.
jQuery("#filtertype").change(function () {
if (jQuery("#posttype").is(":checked")) {
jQuery("#postblock").slideDown("slow");
} else {
jQuery("#postblock").slideUp("slow");
}
if (jQuery("#taxonomycat").is(":checked")) {
jQuery("#taxonomyblock").slideDown("slow");
} else {
jQuery("#taxonomyblock").slideUp("slow");
}
if (jQuery("#taxonomytag").is(":checked")) {
jQuery("#taxonomyblocktag").slideDown("slow");
} else {
jQuery("#taxonomyblocktag").slideUp("slow");
}
if (jQuery("#fieldjeskey").is(":checked")) {
jQuery("#fieldblock").slideDown("slow");
} else {
jQuery("#fieldblock").slideUp("slow");
}
if (jQuery("#sliderme").is(":checked")) {
jQuery("#sliderblock").slideDown("slow");
} else {
jQuery("#sliderblock").slideUp("slow");
}
});
This works like it should; it gets the ID of the checkbox <input>
and for every <input>
(#filtertype, #taxonomycat etc.) it will show or hide a <div>
(#postblock, #taxonomyblock etc.)
It may be smarter to get the ID of every <input>
and toggle the slideUp
, slideDown
function.
How can this be done?
Upvotes: 2
Views: 138
Reputation: 337656
Firstly, rather than have a list of id
selectors, put a single class of each of those checkboxes, along with a data
attribute to specify the relation. Something like this:
<input type="checkbox" name="posttype" class="filter-checkbox" data-rel="postblock" value="foobar" />
Then in javascript you can simplify all the code above to the following:
jQuery("#filtertype").change(function() {
$('.filter-checkbox').each(function() {
var func = this.checked ? 'slideDown' : 'slideUp';
$('#' + $(this).data('rel'))[func]('slow');
});
});
Upvotes: 4
Reputation: 324760
It could be more efficient by not using jQuery.
Replace all of your jQuery("#someID").is(":checked")
with
document.getElementById('someID').checked
, and short of writing your own lightweight animation engine that's as good as you'll get.
Or you can go down the dark path of obscurity:
jQuery("#postblock")["slide"+(document.getElementById('posttype').checked ? "Down" : "Up")]("slow");
But that's probably not a good idea :p
Upvotes: 4