7

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.)

freefaller
  • 19,368
  • 7
  • 57
  • 87

1 Answers1

9

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") )

j08691
  • 204,283
  • 31
  • 260
  • 272
  • I'm going to use the comment by the OP on the duplicate question... "Ok, so I am an idiot and need to RTFM before I ask questions.". Thanks for your answer... will mark as answer when I can – freefaller Feb 27 '17 at 15:19
  • In my exceptionally limited defence, I read the first of the definitions (`.toggle( [duration ] [, complete ] )`) and assumed if I passed in a boolean it would be taken as the `[duration]`... you are completely correct that I failed to continue down the definitions – freefaller Feb 27 '17 at 15:21
  • 1
    @freefaller don't sweat it; happens to all of us – j08691 Feb 27 '17 at 15:21
  • If you are passing any variable, assure to force it to a boolean, `.toggle(!!show)` otherwise you might pass `undefined` and then it will just toggle... good luck finding the bug afterwards. – estani Feb 17 '21 at 17:49