views:

74

answers:

2

Hi,

I have some code that works fine in FF but not in IE. I have read other posts saying that the Jquery live method does not support change events but I am using a click event. Here is my code, it is inside $(document).ready(function():

$("a").live("click", function(e) { 
        alert("link clicked");
        //do stuff
    });

If FF the alert is fired but not in IE. When I use $("a").click it works fine, the problem is that I need to the function to be applied to links that do not exist when the page is first loaded (they will be created via ajax calls at a later stage).

Do I have any options here. We are using jquery-1.4.1.min.js.

Thanks in advance

A: 

Elements should exist in the DOM at the moment you attach the live event. If later they are recreated (for example in an ajax callback) you don't need to reattach the event handler again. If elements don't exist at page load you can attach the live event when they are loaded, but if you do this then probably you no longer need the live event as you can directly attach the click event.

Darin Dimitrov
I am not following you at all. I am working on a large project and I do not have control over all of the code. I need a method to be called on the click of every "a". When I use the click event some of the links (the ones that are loaded after the page loads because they take a long time) do not get picked up by the jquery click. When I use live it works but not in IE. I have to use jquery to intercept all links as I do not have access to the code containing the link itself. Hope this makes sense
Kaskade
+1  A: 

if those links are within a specific content, you can use:

$('#link_container_id').delegate('a', 'click', function(e){
   alert('link clicked');
});

.delegate() will watch if there are any events (click in your case) bubbling up, if so it checks for the target and compares it to 'a' in your case. Should work, but untested.

Kind Regards

--Andy

jAndy
well the context is the entire page. Can I specify this for the entire body of the page?
Kaskade
it should, $(document.body).delegate() for instance.
jAndy
@jAndy - That's almost the same as using `.live()`, `$(document)` would be *exactly* the same, not sure how this would resolve the issue of the bubbling not happening.
Nick Craver
well the binding works fine in FF with .live() just not in IE. Testing this out now so I'll be back with an update
Kaskade
@Nick - yes thats pretty much true, its actually the same. Maybe I don't get the problem right. In IE both methods work fine for me on dynamically created anchors.
jAndy
Thanks Andy, that worked, I don't know why the .live doesn't work but as long as I have a solution that does work!
Kaskade