I’m looking for a solution to the following problem:
1) I’m loading a couple of text lines, some of them containing a link to a footnote like this: 1). These lines are embedded in an <a> element (see below)
2) when the user clicks on such a line, the corresponding footnote text should show up for some seconds
3) in a static context, there is no problem to accomplish this behaviour. However, my problem is that the lines loaded under 1) vary from call to call, and so do the connected footnote texts. Therefore, I’m trying to find a way to dynamically connect the (varying number of) javascript event handler functions to their corresponding footnote texts.
So far, I have managed to come up with the following code – which doesn’t work as desired, however:
function displayData(data) {
$('#statisticTable').html(data); // coming from a datapage.php
for (i = 0; i < 15; i++) { // max. 15 footnotes per page
// The lines containing a hint are looking as follows:
// <a href="" id="nt1" class="ui-link">Any Title <sup>1)</sup></a>
$('#nt' + i).click(function() {
if (!notesAlreadyLoaded) {
$.get('notes.php', 'some params', processNotes);
// a footnote looks like this:
// <div class="reg_footnote" id="note1">Comment on Any Title: ... </div>
notesAlreadyLoaded = true;
}
else
// Where can I get the number 'note_index' from?
// Trying to read the 'id' attribute from the <a> element doesn't work?
$("#note"+note_index).fadeIn(800).delay(3000).fadeOut(800);
});
}
$.mobile.changePage('#data');
}
function processNotes(notes) {
$('#footnotes').html(notes);
// where can I get the number 'note_index' from?
$("#note"+note_index).fadeIn(800).delay(3000).fadeOut(800);
}
Apparently, the event handler functions are created correctly, and they get called in the right moment, too. However, I can’t find a way to tell them which footnote they should fade in.
Use event delegation. Don’t bind events onto the elements themselves, but rather onto an ancestor element that will never be removed or replaced:
In the above code we could bind directly to the anchor:
But as you pointed out, this doesn’t work for new links that may be dropped into the DOM at a later date. As such, we should delegate the job to the parent element:
Now the event is bound to the ancestor element, which lets us respond to any anchor click that should happen within it.
When a click event bubbles up to the
#mylistelement, coming from an item that matches our.fooselector, ourdoSomethingfunction will be triggered.