Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the button using jQuery functions not hiding my divs with classes: .red, .yellow – when I click it?

I made this function to hide the divs that are not the color of the button wording. Nothing seems to happen when I press the button, no class is hidden. I already linked the js into the html file. It I tried adding toggleClass with a class that is visibility:hidden but it doesnt seem to work as well. I think there could be the problem with the button

$(document).ready(function() {

  $('#option_blue').click(function() {

    $('.red', '.yellow').toggle();

  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button id="option_blue">blue</button>
<div class="flex">

  <div class="blue">
    <!--The divs are boxes containing content -->
  </div>

  <div class="red">
  </div>

  <div class="yellow">
  </div>

  <div class="blue">
  </div>

  <div class="red">
  </div>

  <div class="yellow">
  </div>

</div>
.flex {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  gap: 5px;
}



.blue {
  height: 100px;
  width: 100px;
  background-color: blue;
}

.red {
  height: 100px;
  width: 100px;
  background-color: red;
}

.yellow {
  height: 100px;
  width: 100px;
  background-color: yellow;
}

/The style for my element boxes/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The selector must be on unique string, the comma is inside the string selector: documentation link.

$('.red, .yellow').toggle();
$(document).ready(function() {
  $('#option_blue').click(function() {
    $('.red, .yellow').toggle();
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button id="option_blue">blue</button>
<div class="flex">

  <div class="blue">
    <!--The divs are boxes containing content -->
  </div>

  <div class="red">
    red
  </div>

  <div class="yellow">
    yellow
  </div>

  <div class="blue">
    blue
  </div>

  <div class="red">
    red
  </div>

  <div class="yellow">
    yellow
  </div>

</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading