I am using PHP and jquery. I am also using Drupal but I think this is general problem and probably not related to Drupal.
I have link on a page:
<a href="/my-module/js/1" class="launch-js">Link</a>
Clicking the link launches a snippet of jquery wich fades in some html.
if (Drupal.jsEnabled) {
$(document).ready(function(){
$('a.launch-js').click(function(){
...
The html which is being faded in also contains
<a href="/my-module/js/1" class="launch-js">Link</a>
But clicking on this link doesn’t work anymore as I expected. The browser loads page /my-module/js/1 instead of updating the current page.
When you load new content, it overwrites your dom element, and since the event is attached to a particular element, it disappears along with the element. One standard solution to this is to use jQuery.delegate() to attach the event to an element higher up on the page, like this:
This works because events in the DOM “bubble”. When you click on an element, it sends a click event to that element as well as every one of it’s ancestors all the way to the top (assuming no custom code stops the propagation). So you can just attach the event handler to an ancestor of the element, and the have the event handler itself determine if the click came from an element you specified. jQuery hides the details of this and provides a nice simple delegation method to do this for you.
And in jQuery 1.7, this method has been superceded by jQuery.on():
Note the I’ve used
bodyas the selector here, but you can use any selector that is an ancestor of all possiblea.launch-jses and will always exist. The deeper in the dom (or put another way, the closer it is, as an ancestor, to the final target elements — a.launch.js in this case), the more efficient it is, because the less dom traversal has to be done to check for the event.UPDATE: Hat tip to @Clive, who points out in the comments that Drupal 6 only supports up to version 1.3 of jQuery. Neither of the above methods (
onordelegate) existed in version 1.3. Instead there was a method called jQuery.live() to accomplish this task, and it worked like this:This method has a few performance drawbacks that the other methods do not (see the api docs for specific details if you’re interested), and it’s also deprecated, so only use it if you have to (i.e. if you’re using jQuery version 1.3 and can’t upgrade).