how to hide and show element by changing css with jquery

2

Good evening, I'd like to know how I can hide and show my div with class clic as checkbox selected. I have several checkbox and as I select or deselect checkbox I want it to show the element and hide if I deselect it. I tried the following 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 unselect the element it would have to hide the class click again and it does not hide anyone could help me?

    
asked by anonymous 21.12.2016 / 22:35

2 answers

4

You have an error in your if .

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

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

    
21.12.2016 / 22:40
2

Suggestion, with another answer accepted ...

$('.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><divclass="hovereffect">
    <input type="checkbox">
    <div class="clic" style="display:none">Olá!</div>
</div>

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

If HTML allows you to even do this 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>
    
21.12.2016 / 22:55