jQuery - add/remove class on click

Viewed 41

I have the following problem on hand: Create two buttons that will show/hide corresponding content underneath. I achieved it using this code:

$(document).ready(function() {
  $("#button2").click(function() {
    $(".content1").hide();
    $(".content2").show();
  });
  $("#button1").click(function() {
    $(".content1").show();
    $(".content2").hide();
  });
});
.content1 {
  display: none;
}

.frequency {
  display: flex;
}

.frequency button {
  border: 2px solid red;
  padding: 25px 20px;
}

.frequency>button:hover,
.frequency>button.active {
  background-color: red;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="frequency">
  <button id="button1">button1text</button>
  <button id="button2">button2text</button>
</div>
<div class="content1">text1</div>
<div class="content2">text2</div>

To take this one step further, I would like the last button that was clicked to stay highlighted (red). I tried playing with addClass, but the code got very messy.

Any suggestions?

1 Answers

in case that more buttons might be added in the future, you can use this solution it'll work for multiple contents without editing your script.

just link your button with content-index attribute then this index with your tab using index attribute

$(document).ready(function() {
  $('.toggle-content').click(function() {

    // get selected tab index
    const contentIndex = $(this).attr('content-index')

    // remove active class from content
    $('.content').removeClass('active')

    // add active class to selcted content
    $('[index=' + contentIndex + ']').addClass('active')

    // remove active class from all buttons
    $('.toggle-content').removeClass('active')

    // add active class to selcted button
    $(this).addClass('active')

  })

});
.content {
  display: none;
}

.content.active {
  display: block;
}

.frequency {
  display: flex;
  gap: 10px
}

.frequency button {
  border: 2px solid red;
  padding: 25px 20px;
}

.frequency>button:hover,
.frequency>button.active {
  background-color: red;
  color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="frequency">
  <button class='toggle-content' content-index='1'>button1text</button>
  <button class='toggle-content active' content-index='2'>button2text</button>
  <button class='toggle-content' content-index='3'>button3text</button>
</div>
<div class="content" index='1'>text1</div>
<div class="content active" index='2'>text2</div>
<div class="content" index='3'>text3</div>

Related