On-click adding and removing background color of a table data(td)
-
14-11-2019 - |
Question
i am using jquery for set background color to the table data and its working fine but i need when user again click the td the color should be deselect. its my script for add color.
java script:
jQuery('td').click(function () { $(this).addClass('active'); });
my css class:
.active{background-color:red;}
when user again click the td the class should remove. How to achieve this.
Solution
jQuery('td').click(function () { $(this).toggleClass('active'); });
toggleClass adds if it doesn't exist or removes if it does exist.
OTHER TIPS
You can use
$(this).removeClass('active');
although you would need to do a check to see if it is already active, which would make your code look like this:
jQuery('td').click(function () {
if($(this).hasClass('active') {
$(this).removeClass('active');
} else {
$(this).addClass('active');
}
});
EDIT:
@Justice is more correct:
jQuery('td').click(function () { $(this).toggleClass('active'); });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow