Raihan
Raihan

Reputation: 4001

How to toggle attribute

I have a List item where if I click on any of the list item it adds an ID "current" .

But If I click again on this list this "current" ID should removed and back to normal again, something like toggling. I am able to add the attribute but not the able to toggle. Any help will be appreciated.

FIDDLE

JS

$('ul li').click(function(){
    $('ul li').removeAttr("id","current");
    $(this).attr("id","current");
});

Upvotes: 0

Views: 815

Answers (3)

PeterKA
PeterKA

Reputation: 24638

DEMO

Here is how to toggle:

$('ul li').click(function(){
    $('ul li').not(this).removeAttr("id");
    if( $(this).attr('id') == 'current' )
    {
        $(this).removeAttr('id');
    }
    else
    {
        $(this).attr("id","current");
    }
});

Use of a css class would be most recommended for work like this:

DEMO

$('ul li').click(function(){
    $('ul li').not(this).removeClass("current");
    $(this).toggleClass('current');
});

Upvotes: 1

Viswanath Donthi
Viswanath Donthi

Reputation: 1821

Try this:

$('ul li').click(function(){
    if($(this).attr("id") == "current"){
       $(this).removeAttr("id");
    }else{
       $(this).attr("id","current");
    }
});

Upvotes: 0

j08691
j08691

Reputation: 207901

It should be $('ul li').removeAttr("id");.

jsFiddle example

On a related note, it's best to use classes instead of IDs for stuff like this.

Update:

To toggle, use classes like:

$('ul li').click(function () {
    $('ul li').not(this).removeClass("current");
    $(this).toggleClass("current");
});

jsFiddle example

Upvotes: 4

Related Questions