Tuesday, April 10, 2012

alpha sorting (filters) with unobtrusive (jQuery) javascript

Often I see code for alpha lists that looks like the following...
<a url="#" onClick="javascript:performFilter('D')" name="D">D</a>
Pretty busy... and that's just the "D" letter...
But there's a much easier way to accomplish the same thing using jQuery (once the dom is instantiated)...
See the complete code below...

BTW, using href="javascript:void(0);" instead of "href="#" will keep the page from scrolling to the top when you click on the associated link.

David

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript">

var letterElem
$(document).ready(function(){

  letterElem = $('#default') // "ALL" to begin with...

  div#alpha a').click(function() {

    letterElem.removeClass("chosen"); // remove previous node's green background

    letterElem = $(this) // cache the selected element node

    var letter = letterElem.text(); // grab the text node

    $('#answer').text(letter); // display the letter selected

    letterElem.addClass("chosen"); // give the selected letter a green background

    // askServerToFilter(letter); // here's your placeholding call to the server for a filtered query

  });

$('div#alpha a').attr("href",'javascript:void(0);'); // a's have to have href value...
});

</script>
<style type="text/css">
a { margin:0 8px 0 8px; padding: 1px 2px 1px 2px;}
a.chosen { background-color:green;color:#fff; text-decoration:none;}
span#answer { font-size:18px; color: blue; font-weight:bold; }
</style>

</head>
<!-- BEGIN HTML WITH NO JAVASCRIPT ANYWHERE -->
<body>
<p>An example of unobtrusive javascript... used to address alpha lists. </p>

<div id="alpha">
<p><a>A</a>|<a>B</a>|<a>C</a>|<a>D</a> ... <a id="default" class="chosen">ALL</a></p>
</div>

<p>Click on the alpha list above to get the letter selected... ANSWER: <span id="answer">?</span></p>
</html>
</body>