Home > OS >  Is there a more efficient way to change the style of the clicked buttons?
Is there a more efficient way to change the style of the clicked buttons?

Time:04-14

I have about 40 button on the project but my example shows only four. My code is very repetitive and wondering if there's a lighter approach or language? I'd like to hide or change style of the clicked button/s.

$("[data-id='1']").on('click', function() {
  $("[data-id='1']").css('visibility', 'hidden');
});
$("[data-id='2']").on('click', function() {
  $("[data-id='2']").css('visibility', 'hidden');
});
$("[data-id='3']").on('click', function() {
  $("[data-id='3']").css('visibility', 'hidden');
});
$("[data-id='4']").on('click', function() {
  $("[data-id='4']").css('visibility', 'hidden');
});
button {
  margin: 20px 0 0 20px;
  padding: 5px 30px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button data-id='1' >1</button>
<button data-id='2' >2</button>
<button data-id='3' >3</button>
<button data-id='4' >4</button>

Thanks http://jsfiddle.net/05cempj7/

CodePudding user response:

This function operates on all elements having the .hope class.

$(".hope").on('click', function() {
  $(this).css('visibility', 'hidden');
});

If clicked on any hope class $(".hope") then $(this) reefers to the element that is clicked on.

  • Related