how to hide and show the element by changing the css with jquery

Asked

Viewed 816 times

2

good evening I would like to know how I can hide and show my div with the class clic as per the checkbox selected. I have several checkbox and as I select or deselect the checkbox i want it to show the element and hide in case I desiccate. I tried it this way:

HTML:

<div class="clic" style="display:none"></div>

jQuery:

if ($(this.checked)) {
    $(this).closest(".hovereffect").find(".clic").css("display", "block");
} else {
    $(this).closest(".hovereffect").find(".clic").css("display", "none");
}

with this code I can insert the element but when I desiccate the element it would have to hide the class clic again and it does not hide anyone could help me?

2 answers

4


There’s a mistake in yours if.

instead of if($(this.checked)) use if(this.checked)

Or maybe his intention was to use the method is jQuery: $(this).is(':checked')

  • thanks guy had not even seen this mistake was himself vlw by the reply

  • Mark the answer as accepted, please.

2

Suggestion, already with another accepted answer...

$('.hovereffect :checkbox').on('change', function() {
  $(this).closest(".hovereffect").find(".clic").toggle(this.checked);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hovereffect">
    <input type="checkbox">
    <div class="clic" style="display:none">Olá!</div>
</div>

So it gets more organized and you use the .toggle() jQuery.

If HTML allows it you could even do it only with CSS, without jQuery... like this:

input:checked + .clic {
  display: block !important;
}
<div class="hovereffect">
  <input type="checkbox">
  <div class="clic" style="display:none">Olá!</div>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.