Question

I'm having an issue with ajax generated selectors.

basically i have a start button in default state. onclick, it starts something, and then the click also brings in a new div from an ajax call with results. one of these items is the stop button. my linked script from the main page has a click event attached to this stop button

<a id="stop">stop</a>

If I put the script inline, in the return call it self that also prints the anchor, i can access it with

$('#stop').click(function() {   });

However, I don't want the script there (as there are multiple items per page and it makes much more sense to have it in the main linked resource). If this call is in the linked sheet from the main page, nothing happens.

Why is this?

Is there another 'document ready' wrapper i should use to address return elements?

Was it helpful?

Solution

If

<div id="container"></div>

is the element which you're appending the results of the ajax call to,

You want to do:

$('#container').on('click', '#stop', function() { console.log('test'); });

Alternatively you could do something like

$('#stop').live('click', function(){ console.log('test'); });

But I wouldn't recommend that if you are going to have a lot of events on the page to handle, because live adds overhead every time it's used.

OTHER TIPS

My understanding of your issue is that the click event you create does not fire for elements added through ajax. When you attach the handler to the click event of an element, this ONLY occurs for those elements which are currently in the DOM. You have a few options to get the behavior you desire.

1) Use the inefficient "live" handler. (inefficiency measured in milliseconds generally)

$('#stop').live('click', function(){});

2) Reattach the event handler after the element has been inserted into the DOM.

$.ajax({
    complete: function(){
        $('#idOfTheElementsYouJustInserted').click(function(){});
    }
});

3) Attach an event handler to a static parent element, so that when the button is clicked, the event "bubbles" up and triggers this event. To refer to the element that created the bubble, you can use event.target where event is the default parameter passed to the function.

$('#staticParentElement').click(function(event) { var elementClicked = event.target;   });

Your main script isn't adding the event to your new element because it was run before the element existed.

Would it work to create the function in the main script and then simply specify the function when you add the event -

main script

var your_function = function() {
    // your code
}

then when you add the div -

$('#stop').click(your_function());

A nicer solution would be Brad M's suggestion of adding the event to a parent and processing it as it bubbles up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top