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' class="hope">1</button> <button data-id='2' class="hope">2</button> <button data-id='3' class="hope">3</button> <button data-id='4' class="hope">4</button>
Thanks http://jsfiddle.net/05cempj7/
Advertisement
Answer
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.