views:

30

answers:

1

I am trying to copy reddit's voting buttons but I'm somewhat new to jQuery so I'm having challenges. My HTML block looks like:

<ul class="karma-controls">
    <li class="karma-control karma-up karma-up-selected"><a href=""></a></li>
    <li class="karma-total">1</li>
    <li class="karma-control karma-down"><a href=""></a></li>
</ul>

The css simply gives .karma-up/.karma-down it's respective karma_up.png and karma_down.png arrow. when the karma-up-selected or karma-down-selected class is added my css just overwrites the background with a more fitting image.

$(this).closest(".karma-up").toggleClass("karma-up-selected");
$(this).closest(".karma-down").toggleClass("karma-down-selected");

Actually does what I want but they are independent of one another. If karma-up is clicked then karma-down needs to be unselected (if previously selected) and vice versa.

I'm thinking I am going to need a lot of if's with hasClass, removeClass and addClass but I want to see what the SO community thinks.

+1  A: 

Here is a solution that uses a single click function between the two items:

$('.karma-down a, .karma-up a').click(function(e){
    var $parent = $(this).parent(),
        up      = $parent.hasClass('karma-up');

    $parent.toggleClass("karma-" + (up ? 'up' : 'down') + "-selected");
    $parent.siblings().removeClass("karma-" + (up ? 'down' : 'up') + "-selected");

    e.preventDefault();
});

So now it toggles the clicked item on and off, but also removes the click stat from the opposing item.

Doug Neiner
Wow haha, thats almost more efficient than I can use! Now to attach some AJAX to this... thanks!