ssdesign
ssdesign

Reputation: 2821

Javascript CSS single selection toggle (vertical list)

I would like to create the following but am not sure what would be the best way to go about it.

I want a vertical list of items on a web page. Each item is click-able. When the user click once one list item, I want to show that it has been selected (by showing a button image in the background. When the click the same item again or clicks any other list item, I want to remove that image and if another item was clicked, the selection image is shown behind that item.

Any suggestions?

Thanks

Upvotes: 2

Views: 758

Answers (3)

namuol
namuol

Reputation: 9996

This is especially pleasurable to do in jQuery. Fiddle: http://jsfiddle.net/HgVmm/3/

HTML:

<ul id='items' class='selectable'>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
</ul>

JS:

// For a single list to act independent of other lists:
$('ul.selectable li').live('click', function () {
    $(this).siblings('li.selected').removeClass('selected');
    $(this).toggleClass('selected');
});

// For all `selectable` lists to act together:
$('ul.selectable li').live('click', function () {
    $('li.selected').not(this).removeClass('selected');
    $(this).toggleClass('selected');
});

CSS:

ul.selectable li { cursor: pointer; }
ul.selectable li.selected { background: red; } /* Style to taste */

Upvotes: 2

sandeep
sandeep

Reputation: 92873

@ssdesign; i know you accepted an answer but may be you can check this one http://jsfiddle.net/sandeep/HgVmm/4/

$('li').click(function(){
    $('li').removeClass('selected');
    $(this).addClass('selected');
});

Upvotes: 1

Brad Christie
Brad Christie

Reputation: 101614

Demo, along with a re-factored version

// catch a click on any of the <li> items
$('li').click(function(){
    // store a reference to the specific <li> that
    // was clicked.
    var $li = $(this);

    // toggle the class (if it's applied, it's removed.
    // if it's removed, re-apply it)
    $li.toggleClass('clicked');

    // Now, if it's applied, remove the class from any
    // other <li> (single item clicked at a time)
    if ($li.hasClass('clicked')){
        $li.siblings().removeClass('clicked');
    }
});

Upvotes: 2

Related Questions