Home > Mobile >  $(this).addClass for multiple onclick='myfunction()'
$(this).addClass for multiple onclick='myfunction()'

Time:04-02

This is my code, buttons are creating dynamically

<button  onclick='myfunction()'>button name</button>
<button  onclick='myfunction()'>button name</button>
<button  onclick='myfunction()'>button name</button>
<button  onclick='myfunction()'>button name</button>

and I want to add class to button which I clicked

function myfunction()
{
  $(this).addClass("active");
}

CodePudding user response:

If you're using jQuery, and you're adding the buttons dynamically, strip out the inline JS, and use event delegation to attach one listener to a parent container to watch for events from your same_name buttons, and then add a class for that clicked button. (I'm using toggleClass in this example.)

$(document).on('click', '.same_name', function () {
  $(this).toggleClass('active');
});
.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button >button 1</button>
<button >button 2</button>
<button >button 3</button>
<button >button 4</button>

CodePudding user response:

Andy's solution is the proper one. If you wish to roll with your own solution, just pass the event to the function.

function myfunction(event){
  let eTar = event.target
  $(eTar).addClass("active");
}
.active { color: red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button  onclick='myfunction(event)'>button name</button>
<button  onclick='myfunction(event)'>button name</button>
<button  onclick='myfunction(event)'>button name</button>
<button  onclick='myfunction(event)'>button name</button>
 

CodePudding user response:

Here's the vanilla JS answer (jQuery isn't necessary at all, for almost nothing in 2022):

document.addEventListener('click', function ({target}) {
  if (target.matches('button.same_name'))
    target.classList.add('active');
});
.active { color: red; }
<button >button 1</button>
<button >button 2</button>
<button >button 3</button>
<button >button 4</button>

CodePudding user response:

use toggleClass

$('.same_name').on('click', function () {
  $('.same_name').removeClass('active'); // if you wants to remove class from other buttons
  $(this).toggleClass('active');
});
.active{
  background-color: #000;
  color: #fff
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button >1</button>
<button >2</button>
<button >3</button>
<button >4</button>

  • Related