Stewie Griffin
Stewie Griffin

Reputation: 9327

trying to understand toggleClass()

I have a simple code, which adds/removes classes:

 clearAndSetLogin: function (row) {

    if ($j('#leademails tr').is('.waslogin'))
        $j('#leademails tr.waslogin').removeClass('waslogin');

    $j('#leademails tr.islogin').removeClass('islogin').addClass('waslogin');     
    row.addClass('islogin');   
 },

can I do the same with toggleClass() ? if so, why that would be more efficient? Thanks!

Upvotes: 0

Views: 237

Answers (3)

Blair McMillan
Blair McMillan

Reputation: 5349

No, toggleClass won't do exactly the same thing (at least not without having most of your existing code there anyway).

If we take the following code (which won't do what you want):

clearAndSetLogin: function (row) {
    $j('#leademails tr').toggleClass(".waslogin");
    $j('#leademails tr').toggleClass(".islogin");
},

and work through it line by line a call to clearAndSetLogin would add waslogin if it isn't there, remove it if it was and do the same thing for islogin. What you have in your code only adds waslogin if it currently islogin.

You could do the .islogin part with toggleClass if you wanted.

Upvotes: 2

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196002

The if part is not needed

so your code needs to be

$j('#leademails tr.waslogin').removeClass('waslogin');
$j('#leademails tr.islogin').removeClass('islogin').addClass('waslogin');
row.addClass('islogin');

the toggleClass will not help in this case as you are operating on different elements in each line (and my assumption is that you have multiple tr elements under the #leademails, and you do not all of them getting the islogin or waslogin class).

Upvotes: 4

hitmanDX
hitmanDX

Reputation: 245

Take a look at jQ's API, http://api.jquery.com/toggleClass/

but yes, this should be what your looking for:

clearAndSetLogin: function (row) {
    $j('#leademails tr').toggleClass(".waslogin");
    $j('#leademails tr').toggleClass(".islogin");
},

Upvotes: -1

Related Questions