Home > Software engineering >  jQuery multiple button show and hide elements when click
jQuery multiple button show and hide elements when click

Time:06-16

I have a multiple buttons has show and hide class. Which is also activate the elements every toggle click. I want to make it a shorter code and make it globally. Please help me how to do it. All I want is to achieve a lesser code and same with the result.. Thank you.

$('.show').on('click', function () {
    $(this).addClass('inactive');
    $('.hide').removeClass('inactive');
    $('.helloworld').removeClass('inactive')
})
$('.hide').on('click', function () {
    $(this).addClass('inactive');
    $('.show').removeClass('inactive');
     $('.helloworld').addClass('inactive')
})
$('.ok').on('click', function () {
    $(this).addClass('inactive');
    $('.cancel').removeClass('inactive');
    $('.thanks').removeClass('inactive')
})
$('.cancel').on('click', function () {
    $(this).addClass('inactive');
    $('.ok').removeClass('inactive');
     $('.thanks').addClass('inactive')
})
<style>
.inactive{
  display:none;
}
button{
  padding:5px 25px;
  color: #fff;
  background-color:#1d9bf0;
  margin-top: 10px;
}
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button >   Show </button>
<button > - Hide </button>
<p >Hello WOrld</p>
<br>
<button >   Ok </button>
<button > - Cancel </button>
<p >Thank you</p>

CodePudding user response:

The technique you're looking for here is DRY, or Don't Repeat Yourself. To do this, look for the common patterns in the logic you have.

In this case each button has its text updated, and it changes the state of it's following sibling. Therefore you can place common class attributes on the elements so that the same JS logic can be applied to them all. From there you can use jQuery's DOM traversal methods to relate the elements to each other, and also data attributes to store custom metadata about the elements which can be used when the click event occurs.

Finally you can use toggleClass() to add/remove the classes to display/hide the elements as necessary.

Here's a working example:

$('.toggle').on('click', e => {
  let $btn = $(e.target);
  $btn
    .text(() => $btn.data($btn.hasClass('show') ? 'hide-text' : 'show-text')).toggleClass('show') // update text
    .next().toggleClass('inactive'); // toggle related content
})
<style>
  .inactive {
    display: none;
  }
  
  button {
    padding: 5px 25px;
    color: #fff;
    background-color: #1d9bf0;
    margin-top: 10px;
  }
</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <button  data-show-text="  Show" data-hide-text="- Hide">  Show</button>
  <p >Hello WOrld</p>
</div>
<div >
  <button  data-show-text="  Ok" data-hide-text="- Cancel">  Ok</button>
  <p >Thank you</p>
</div>

  • Related