How do I write a click event that acts on an element not yet loaded into the DOM?
Scenario:
- native-btn is a div loaded at document ready.
- ajax-loaded-element is a div that appears after an ajax form executes a series of client-side events
My event is as follows:
$(".native-btn").click(function() {
$(".ajax-loaded-element").fadeOut();
});
I can't seem to get the .ajax-loaded element to respond. I know that .live() is deprecated, and the .on() event only applies to interacting directly with a newly inserted element, not acting on it by means of a secondary action. Is there another usage of .on() that I'm missing?
Thanks!
UPDATE
I am now using the .on() event to access the . ajax-loaded-element div. However, while it responds to basic events like .hide() and .css(), it doesn't respond to .trigger(), which is what I ultimately need it to do.
$(document).on("click", ".native-btn", function() {
$('.ajax-loaded-element').trigger('click');
$('.ajax-loaded-element').css("background-color","red");
});
Background changes to red, but trigger doesn't fire. I should add that the default functionality of the .ajax-loaded-element that is being loaded by the CMS advances a page on an ajax form. I am trying to trigger it remotely because I want to add custom animations before and after the default functionality.
THE WHOLE SCOOP
I am using a multipage webform in Drupal, which shows up as a block on a page. Because I've assigned ajax client-side functionality to it, it dynamically inserts "PREV" and "NEXT" divs to advance the form as needed.
From a UX perspective, I want to fade the whole form out, let the form advance to the next page, then fade the form in, instead of a blink-of-an-eye change wherein the user may not perceive that the form has advanced. I don't have access to the webform functionality, so I'm trying to do it with jQuery and trigger. The basic markup is:
<div id='webform'>
...form code...
<div class='ajax-loaded-next'>Next</div>
<div class='ajax-loaded-prev'>Prev</div>
</div>
<div class='native-btn-next'>NEXT</div>
<div class='native-btn-prev'>PREV</div>
$(document).on("click", ".native-btn-next", function() {
$('#webform').fadeOut();
$('#webform .ajax-loaded-next').trigger('click');
$('#webform').fadeIn();
});
$(document).on("click", ".native-btn-prev", function() {
$('#webform').fadeOut();
$('#webform .ajax-loaded-prev').trigger('click');
$('#webform').fadeIn();
});
Looks like this: (ajax NEXT/PREV are white, native NEXT/PREV are black)
As you can see, it starts with only the Next button, which works like a charm. Webform fades out, the ajax-loaded-next trigger clicks, the page advances, webform fades in.
But on page 02, the ajax-loaded-prev button shows up:
This was obviously not in the DOM when the form loaded. My native-btn-prev fades the webform in and out, but doesn't trigger click.
Hope that makes sense...