Ando
Ando

Reputation: 1847

jquery toggle between classes from two different buttons

I've been having trouble with a button that I'm trying to get my head around.

Basically I have two buttons. Button #1 is on the side bar and has two states with the following style

.Bt, .BtT {
height: 129px;
cursor: pointer;
background: url('../images/sideBtns.png') no-repeat;  
}

.BtT{
background-position: 0 -129px;
}

Then in my HTML <div id="closeRefs" class="Bt"> (this is the one on the side) And the second one which is

<a class="openRef" ...> ... </a>

Then my javaScript is as follows

    $("#closeRefs").click(function () {//SIDE BUTTON
        $(".Bt").toggleClass('BtT');
    });

    $(".openRef").click(function () {//REFERENCES OPEN
        $(".Bt").removeClass('Bt').addClass('BtT');
    });

This works up as follows: Side button switches between the background-position, the reference button is able to also switch on the side button it is clicked (if the side button is not on). The problem persists when I click on the reference button, it switches on the side button and then when i click the side button it doesn't switch itself off.

Upvotes: 0

Views: 696

Answers (2)

JayMoretti
JayMoretti

Reputation: 265

If I understood you correctly, this is what you're trying to do: http://jsfiddle.net/KQ7EQ/

What Arun said is correct, you're removing Bt leaving the target div with nothing to go back to. Also, you're not setting a 'reset position'.

For example: When you remove BlT there's nothing telling the background to go back to its initial position.

If you add:

.Bt{
    background-position: 0 0;
}

that will tell the background image to reset its position.

Also if you want Bl to be gone when BlTis active and vice-versa, you should use:

$bt.toggleClass('Bt').toggleClass('BlT');

Since Bt is there from the start, it will be removed on when you're adding BlT and the opposite when you call it again.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

It could because you are removing the class Bt when you click openRef. So when you click on closeRefs there is no element with class Bt

var $bt = $(".Bt");
$("#closeRefs").click(function () {//SIDE BUTTON
    $bt.toggleClass('BtT');
});

$(".openRef").click(function () {//REFERENCES OPEN
    $bt.removeClass('Bt').addClass('BtT');
});

Upvotes: 1

Related Questions