Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery show/hide based on variable (not toggle) [duplicate]

Tags:

jquery

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

like image 775
freefaller Avatar asked Feb 27 '17 15:02

freefaller


1 Answers

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

like image 76
j08691 Avatar answered Nov 04 '22 00:11

j08691