Mathias Fyrst Jakobsen
Mathias Fyrst Jakobsen

Reputation: 139

Toggle function Javascript

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

Upvotes: 1

Views: 244

Answers (3)

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76910

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

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

Upvotes: 6

sinsedrix
sinsedrix

Reputation: 4795

Why not use .toggleClass() ?

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

Upvotes: 1

musefan
musefan

Reputation: 48435

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.

Upvotes: 3

Related Questions