In jQuery (I'm currently using 1.11.4), is there any inbuilt helper function to allow you to show/hide elements based on a variable?
For instance, at the moment to show/hide something based on a checkbox I do something like these two examples...
$("#myChk").on("click", function() {
if ($(this).is(":checked")) {
$("#otherEl").show();
} else {
$("#otherEl").hide();
}
});
$("#myChk").on("click", function() {
var $otherEl = $("#otherEl");
($(this).is(":checked") ? $otherEl.show() : $otherEl.hide());
});
Is there a single inbuilt function that I can't easily find in the documentation that allows something like...
$("#myChk").on("click", function() {
$("#otherEl").showOrHide($(this).is(":checked"))
});
I'm pretty sure there isn't anything, but I thought I'd ask just in case.
I'm aware of .toggle()
but that is based on the current visibility of the element, not an external variable.
(And if anybody is aware of anything similar for .slideUp
and .slideDown
that would also be useful.)
You just needed to read further down in the documentation. .toggle()
allows you to pass true/false to set the display:
http://api.jquery.com/toggle/#toggle-display
display
Type: Boolean
Use true to show the element or false to hide it.
So you can pass $(this).is(":checked")
to it, e.g. .toggle( $(this).is(":checked") )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With