JQuery and AJAX content

I ran into a little problem with links in the content that was loaded into the page with jQuery. It turns out that jQuery attaches (binds) its functions to whatever objects (anchors tags in this case) you specify when the page is loaded. If more content is added later via Ajax, anchor tags in that content will not have the functions attached. The Web site has 4 links for navigation created with this HTML:

<ul id="tabs">
<li id="about" class="active"><a href="about.html" id="about">About</a></li>
<li id="recordings"><a href="recordings.html" id="recordings">Recordings</a></li>
<li id="comments"><a href="comments.html" id="comments">Reviews & Comments</a></li>
<li id="audio"><a href="audio.html" id="audio">Audio</a></li>
  </ul>
The links are styled into tabs with CSS. (You can find a discussion of the CSS used in the article "Simple Tabs and Ajax with Jquery".) When a user clicks a tab the following javascript code ajaxes the specified content into the page and handles making the chosen tab "active."

$(document).ready(function() {  // do stuff when DOM is ready
 $("ul#tabs li a").css("text-decoration","none");
 $("div#overlay").hide();
 $("ul#tabs li, ul#tabs li a").click(function(){
   var whichtab = $(this).attr('id');
   var theurl = whichtab + ".html #content";
   var thetab = "li#" + whichtab;
   $("#loadarea").load(theurl);
   $("ul#tabs li").removeClass("active");
   $(thetab).addClass("active");
   // this fixes the problem
   if (whichtab == "recordings") {
	$.getScript('nodebox.js');
	}
   return false;  // prevents default behavior of the link
  });
});
Note that by using links, the Web site "degrades gracefully" if the user has javascript turned off.

Where the problem occurred was that one of the pages (recordings) had a list of links to each recording which I want to have open in an overlay. I originally put the code for that in with rest in a separate function.

  $("a.cdlink").click(function(){
    var mylink = $(this).attr('id');
    var myurl = mylink + ".html #content";
    $("#overlay").load(myurl);
    $("#overlay").show();
    $("#closer").show();
    $("#holder").show();
    return false;
  });
	
  $("div#holder, div#closer").click(function(){
    $("#overlay").hide();
    $("#closer").hide();
    $("#holder").hide();
  });
	
  $("div#overlay").click(function(){
       //do nothing
  });
But, as mentioned above, the function will not be attached to links that are loaded later.

My solution to this problem was to move this code into a file of its own named nodebox.js, (wrapping it in its own document.ready function), and calling it with jQuery's .getscript method at the end of the tab handling function only if the content that was loading was "recordings.

// this fixes the problem
   if (whichtab == "recordings") {
      $.getScript('nodebox.js');
   }
Problem solved. And good to know.

There is some discussion of this problem at the jQuery Web site.