Issue
This is my code, buttons are creating dynamically
<button class="same_name" onclick='myfunction()'>button name</button>
<button class="same_name" onclick='myfunction()'>button name</button>
<button class="same_name" onclick='myfunction()'>button name</button>
<button class="same_name" onclick='myfunction()'>button name</button>
and I want to add class to button which I clicked
function myfunction()
{
$(this).addClass("active");
}
Solution
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 class="same_name">button 1</button>
<button class="same_name">button 2</button>
<button class="same_name">button 3</button>
<button class="same_name">button 4</button>
Answered By - Andy
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.