Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove selected class jquery

I've got the following HTML:

<a href="#">img/a.jpg</a>
<a href="#">img/b.jpg</a>
<a href="#">img/c.jpg</a>

For selected links I've got the following:

$(function() {
            $("a").click( function( )
            {
            var current = $(this);
            var name = current.attr('href');
            current.addClass("selected");
            var prev = current.closest("a").find("a.selected");
            prev.removeClass("selected");
                return false;
            });
        });

The problem is that after I click some link the previous one I clicked won't deselect(remove class selected). Any help will be greatly appreciated.

like image 243
George Avatar asked Mar 11 '26 11:03

George


1 Answers

You could remove all elements that have a class of selected first, then apply your selected class to the current one.

$("a").click(function( {
    var current = $(this);
    var name = current.attr('href');

    //Remove all
    $('.selected').removeClass('selected');

    //Add to current
    current.addClass("selected");

    return false;
});
like image 77
Jason Kaczmarsky Avatar answered Mar 14 '26 02:03

Jason Kaczmarsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!