Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "this" in an onclick function

I have TRs that are added dynamically after the page is loaded. When they are clicked, I want to add the class "Active" to them. Here is what I have so far:

<tr onClick="makeActive(this);"><td>....</td></tr>

<script>
function makeActive(element){$('.Active').removeClass('Active');element.addClass('Active');}
</script>

The function runs, and removes the "Active" class from any rows that currently have it applied...but it fails to add the class to the clicked row.

Thanks for any help!

like image 517
Alan Avatar asked Dec 04 '22 02:12

Alan


2 Answers

this references a DOM element, you have to wrap it inside a jQuery object first to apply a jQuery method to it.

$(element).addClass('Active');
like image 141
Fabrício Matté Avatar answered Dec 17 '22 22:12

Fabrício Matté


You were close:

<tr onClick="makeActive(this);"><td>....</td></tr>

<script>
function makeActive(element){
    $('.Active').removeClass('Active');
    $(element).addClass('Active');
}
</script>
like image 29
Adriano Carneiro Avatar answered Dec 17 '22 22:12

Adriano Carneiro