Saturday, 12 June 2010

JQuery Tip: Select List Item with Deselect

JQuery LogoHow do select an item from a list? Well this is what I came up with as part of my iPhone/iPad experiments. Using JQuery, a click event is bound to each <li> element. When an item is clicked, the picked class is assigned to that item. The background is changed to show the selected item.



One additional feature of this example, when a selected item is clicked, it is deselected. This is accomplished by a simple check if the current item has the picked class assigned. JQuery makes this code really simple.

See Example

Here is a snippet of the source code.



 8:  <style type="text/css">
9:.ThinListTable { width:480px;}
10:.ThinListTable ul{ list-style-type:none; border:2px solid black; padding:0px; border-bottom:0px;}
11:.ThinListTable li{ border-bottom:2px solid black; padding:4px; margin:0px;}
12:.picked{ background:#EDEDED; }
13: </style>
14:<script type="text/javascript">
15:
16:// View Source
17:function getSource(){
18: window.open("view-source:" + location.href);
19: return;
20:}
21:
22:// Mouse Handler
23:function mouseHandler(e){
24: // Add Picked Class
25: if ($(this).hasClass('picked')) {
26: $(this).removeClass('picked');
27: } else {
28: $(".picked").removeClass('picked');
29: $(this).addClass('picked');
30: }
31:}
32:
33:function start(){
34: // Bind all li
35: $('.ThinListTable li').bind('click', mouseHandler);
36:}
37:
38:$(document).ready(start);
39:</script>
40:


Update: Changed the link to the example page. Moved it on the server.

No comments:

Post a Comment