HTML and CSS Reference
In-Depth Information
$(evt.target).siblings() .andSelf( ).toggleClass( 'rowHighlight');
});
The next problem is the td element that contains the time element. If the time element is
clicked, the list of siblings will be empty, since the time element does not have any sib-
lings. Before finding the siblings we therefore need to first find the closest td element to
the one clicked.
As mentioned earlier, the closest function begins by examining the selected element, and
only ascends the tree if that does not match the requirements. Therefore, the closest td to a
td is itself, but the closest td to a time element is its parent.
The following code therefore meets our requirements:
$('tbody tr').click(function(evt) {
$(evt.target).closest( 'td').siblings( ).andSelf( ).toggleClass( 'rowHighlight');
});
Finally, note that we are using the toggleClass function. Rather than checking whether the
elements have the class rowHighlight , and adding it if they don't, and removing it if they
do, we can let jQuery do the work for us.
In the examples above we are adding event listeners to elements in the document when the
page is loaded. A complication with event listeners is that we might want to add them to
elements that are not in the document yet. Due to the fact we can dynamically add elements
to the DOM, we may want event listeners automatically added to these elements when they
meet specified selection criteria.
If we consider the case of the event listener that highlights selected rows in the table, we
may want this to work even if rows are dynamically added to the table after the page has
loaded.
Fortunately jQuery has an elegant solution to this problem using the on function. The first
part of the solution involves specifying the portion of the document that will contain any
new elements, in our case that may be:
$('#tblTasks tbody')
We could alternatively say we want to add the event listener to any new elements anywhere
in the document with:
$(document)
Next we specify the type of event listener we want to attach, the type of element we want
the event listener added against, and the callback we want executed.
Search WWH ::




Custom Search