user275074
user275074

Reputation:

Toggle class on link click

I'm trying to toggle a class for a link when it is clicked so it either shows plus to expand or minus to reduce but I can't get it working.

My jQuery is as follows:

$(".viewdetails").click(function() {
    $(this).toggleClass('viewdetailsoff');
    $(this).parents("tr").next().toggle();
    return false;
 })

My initial link

<a class="viewdetails" title="View History" href="">History</a>

Upvotes: 0

Views: 2734

Answers (1)

Nick Craver
Nick Craver

Reputation: 630637

If it's just the image that isn't working, make sure .viewdetailsoff is defined after .viewdetails in the CSS, like this:

.viewdetails {
   background-image: url(minus.jpg);
}

.viewdetailsoff {
   background-image: url(plus.jpg);
}

Regardless of class order on the element itself, e.g. it'll be class="viewdetails viewdetailsoff", the order in the CSS is what determines which one wins. Or, you could toggle both classes, effectively swapping them using .toggleClass() like this:

$(this).toggleClass('viewdetails viewdetailsoff');

Upvotes: 1

Related Questions