Reputation: 231
I'm developing a service which allows users to create teams and challenges, as well as individual accounts. Each team and challenge has a unique "ownerID" and each user has a "userID". The main user splash page consists of three accordions: Teams, Challenges and Settings, which, upon selection, display a series of buttons. After clicking a button, an empty div is populated with data from a separate page. And then I run into the aforementioned problem. After loading the external page data for challenges, which contains a drop down list and either a user join or team join button dependent on the selection. The problem is, I want to be able to click on either button and then call a function, but, I can't say:
$('#userJoin').on("click", function() {
var challengeID = $('#challengeSelect').val();
var userID = $('#userID').val();
if (challengeID != 0 && userID != 0) {
joinUserToChallenge(challengeID, userID);
}
});
I'm assuming this is because that function currently lives in the document.ready section, but I'm drawing a blank on how to integrate this into the JS file. Any help would be greatly appreciated, as always.
Upvotes: 0
Views: 612
Reputation: 6030
as I understood your problem correctly this the exact case where jQuery's delegate
method should be used: jQuery delegate method. Description from the documentation:
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
Before jQuery 1.7 there was a method called live
, but now it is deprecated, so you should use delegate
Upvotes: 1
Reputation: 3339
This function should work, if you put it in the callback for the ajax code that loads the content with your buttons. .on()
will only recognize elements that are in the DOM when the page is loaded, and won't catch inserted elements, unless you tag it to a parent that exists when the page is loaded.
However, creating the function and binding with the ajax callback should take care of the problem.
Upvotes: 1
Reputation: 3627
I'm not sure if I understood you correctly, but here is a solution - how to attach event to specific element of loaded content:
$(ElementWhichContainsLoadedContent).on('click', 'ButtonSelector', function()
{
// Your code
});
Upvotes: 1