Home > Blockchain >  jQuery active inactive button globally
jQuery active inactive button globally

Time:06-15

I have multiple of buttons has active and inactive class. I want to make it a shorter code and make it globally. Please help me how to do it. and also added an element which is show and hide for every clicking button has active.

$('.show-btn').on('click', function(){
    $(this).addClass('active');
    $('.hide-btn').removeClass('active')
    $('.p-thanks').removeClass('inactive')
})
$('.hide-btn').on('click', function(){
    $(this).addClass('active');
    $('.show-btn').removeClass('active')
    $('.p-thanks').addClass('inactive')
})
$('.approve').on('click', function(){
    $(this).addClass('active');
    $('.disapprove').removeClass('active')
    $('.p-approve').removeClass('inactive')
})
$('.disapprove').on('click', function(){
    $(this).addClass('active');
    $('.approve').removeClass('active')
    $('.p-approve').addClass('inactive')
})
$('.agree').on('click', function(){
    $(this).addClass('active');
    $('.disagree').removeClass('active')
    $('.p-agree').removeClass('inactive')
})
$('.disagree').on('click', function(){
    $(this).addClass('active');
    $('.agree').removeClass('active')
    $('.p-agree').addClass('inactive')
})
<style>
.active{
    background-color: blue;
    color: white;
  }
.inactive{display: none;}
.btn{padding: 5px 20px;}
div{margin-top:20px;}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <button >Show</button>
  <button >Hide</button>
  <br>
  <p >Thank you</p>
</div>
<div>
  <button >Approve</button>
  <button >Disapprove</button>
  <br>
  <p >Approve</p>
</div>
<div>
  <button >Agree</button>
  <button >Disagree</button>
  <br>
  <p >Agree</p>
</div>

All I want to achieve is a less code .

CodePudding user response:

You can use siblings() to access DOM elements as mentioned below:

$('.btn').on('click', function(){
    $(this).addClass('active');
    $(this).siblings('.btn').removeClass('active');
    $(this).siblings('p').toggleClass('inactive');
});
<style>
.active{
    background-color: blue;
    color: white;
  }
.inactive{display: none;}
.btn{padding: 5px 20px;}
div{margin-top:20px;}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <button >Show</button>
  <button >Hide</button>
  <br>
  <p >Thank you</p>
</div>
<div>
  <button >Approve</button>
  <button >Disapprove</button>
  <br>
  <p >Approve</p>
</div>
<div>
  <button >Agree</button>
  <button >Disagree</button>
  <br>
  <p >Agree</p>
</div>

  • Related