difference between toggleclass and addclass

I am working with jquery and attempting to add a class to a table on the selection of that table row.

I was initially using the following code -

$(this).parents("tr").toggleClass("over", this.clicked);            

For some reason, that wasn't working in only some instances where there was already a class assigned. Before I went too crazy with any troubleshooting, I changed it to the following -

$(this).parents("tr").addClass("over", this.clicked);           

This new option appears to be working fine.

My question is whether one option above is better than the other.....Should I be using toggleClass instead of addClass, or is addClass sufficient?

thanks for any thoughts.

Answers


addClass does just that, adds the class to the element.

toggleClass on the other hand does THAT, toggles the class, removing it if it's there, otherwise adding it, but optionally taking a boolean value (true/false) to determine if the object should be added (true) or removed (false).

toggleClass probably wasn't working for you in the instances where this.clicked was false, which is expected behavior. The argument you're passing in addClass has no effect, since it ALWAYS adds the class.

Conclusion:

Use toggleClass for toggling classes, use addClass for adding classes.


Need Your Help

iOS: Issues with sending unicode text on server

ipad unicode utf-8 ios5.1 unicode-string

I have come across really frustrating issue related to Unicode text and I am not able to do anything more to fix it. I am using following code to store English and Japanese texts on server from iPa...

Providing MySQL users with just the minimum privileges

mysql privileges

For a web application, when creating the user which will connect to the MySQL database, you have the choice of privileges. Assuming that the only actions intended to be done by that user are

Export to CSV using Reporting Services Express 2008 R2

.net .net-3.5 reporting-services ssrs-2008

I am running SQL Server 2008 R2 Express with Advanced Services, with Reporting Services properly configured. I need to be able to export certain reports to CSV, however this is unsupported in the E...