None

jQuery Click Event

December 19, 2009

Here's some example code for handling a click event on a header, then loading some html from a URL into the next div down the page.

HTML

This HTML was generated from a django template, so there was one h3 per year.

<div id="years">
{%for year in Years %}
<h3 class="expand-link"><span class="year">{{ year }}</span> -
   <span class="label">Show</span></h3>
<div class="year-contents"></div>
{%endfor%}
</div>

JavaScript/jQuery

In this code we bind the click event, and then look at the text on the link to see whether we should be expanding or contracting. (Probably better to do this with data storage on the dom node). If we are loading, then we show a prompt and then dynamically load some HTML from a URL. This HTML just contains a table. There's a callback on that load call to update the label text to Close. If it is clicked when we're showing the Close prompt then we just remove the table HTML from the document.

$('#years h3').bind('click', function(){
        if ($(this).find('.label').text() === 'Show'){
            var lHeadNode = $(this)
            lHeadNode.find('.label').text('Loading...');
            var lUrl = '/users/{{User.username}}/year/' + lHeadNode.find('.year').text() + '/';
            var lNode = $(this).next('.year-contents');
            lNode.load(lUrl, function(){
                lHeadNode.find('.label').text('Close'); 
            });

    } else {
        $(this).next('.year-contents').html('');
        $(this).find('.label').text('Show');
    }
});