1

I'm trying to make a toggle that toggles between two classes when clicked on the object with function "openclose(j)". I tried making the script only removeClass("arrow-down"), which works fine, but it wont addClass("arrow-up"). This is really annoying to deal with :)

    function openclose(j){
        if(jQuery('#div_'+j).hasClass("arrow-down")) {
            jQuery('#div_'+j).removeClass("arrow-down").addClass("arrow-up");
        }
        if (jQuery('#div_'+j).hasClass("arrow-up")) {
            jQuery('#div_'+j).removeClass("arrow-up").addClass("arrow-down");
        }

        jQuery('#collaps_'+j).toggle(
            function () {

            }
        );
    }

Any help is much appreciated,

Regards, Mathias

1
  • As a side note, you should look into using toggleClass :) Commented Feb 21, 2012 at 12:06

3 Answers 3

6

You could use toggleClass() which does what you require:

function openclose(j){
    jQuery('#div_'+j).toggleClass("arrow-down").toggleClass("arrow-up");
}
Sign up to request clarification or add additional context in comments.

1 Comment

Great! this helps out perfectly!
3

Use an else if statement...

function openclose(j){
    if(jQuery('#div_'+j).hasClass("arrow-down")) {
        jQuery('#div_'+j).removeClass("arrow-down").addClass("arrow-up");
    }
    else if (jQuery('#div_'+j).hasClass("arrow-up")) {
        jQuery('#div_'+j).removeClass("arrow-up").addClass("arrow-down");
    }

    jQuery('#collaps_'+j).toggle(
        function () {

        }
    );
}

The problem is that you are removing the "arrow-up" class immediate after you add it!

Alternatively you could consider using the toggleClass JQuery function.

1 Comment

jQuery has a toggleClass() function.
1

Why not use .toggleClass() ?

jQuery('#div_'+j).toggleClass("arrow-down").toggleClass("arrow-up");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.