Question

I'm trying to get a links background image to toggle or swap on click for an FAQ accordion expand/contractable div using javascript.

I've gotten things working based on this jsfiddle example (http://jsfiddle.net/QwELf/)

You can see my page working here (http://bit.ly/1hfgcGL)

The problem comes in when you click one of the toggle links a 3rd time. It gets the wrong background image and is then out of sync with how it should look.

Right arrow > for contracted state and downward arrow for expanded state are how they should be but the opposite shows up.

It seems to work just fine in the jsfiddle on the 3rd or more clicks any idea what's going wrong with mine?

Script

<script type="text/javascript">
  function changeArrow(element){

var arrow = element;

if(arrow.className == 'background_one'){

  arrow.className = 'background_two';

} else {

  arrow.className = 'background_one';

}

}
</script>

CSS

.background_one { text-decoration: none; padding-left: 26px; background: url(http://skmgroupwork.com/suntrust/landingpages/307m/chevright.gif) center left no-repeat;}
.background_two { text-decoration: none; padding-left: 26px; background: url(http://skmgroupwork.com/suntrust/landingpages/307m/chevdown.gif) center left no-repeat;}

HTML

<a class="background_one" data-toggle="collapse" data-target="#demo4"    onClick="changeArrow(this)">If I transfer my balance to a new Access 3 Equity Line, what will my interest rate be?</a>
Was it helpful?

Solution

You need to check if it has class, not if it is, as you have several on times. As you use jQuery you can use .hasClass(), .addClass() and removeCLass(). You might also want to look at .toggleClass().

function changeArrow(element) {
    var $arrow = $(element);
    if ($arrow.hasClass('background_one')) {
        $arrow.removeClass('background_one');
        $arrow.addClass('background_two');
    } else {
        $arrow.removeClass('background_two');
        $arrow.addClass('background_one');
    }
}

OTHER TIPS

That is happening because the className also contains the class collapsed the second time it's clicked.

I used IE's debugger and found this:

enter image description here

Perhaps you could use contains instead of equals, like the following (untested, but should work):

function changeArrow(element){
    element.className = (arrow.className.contains('background_one') ? 
                          'background_two' : 
                          'background_one');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top