I am using multiple Blueimp File Upload plugins in ajax-loaded html :
$('.edit').click(function(){
$( "#details" ).show();
$('#details div').html(ajax_spinner).load(script.php, "parameters");
});
So when you click something class="edit" a new div id="details" is shown (but it was in the DOM when document.ready) and script.php returns a form id="upload" (which is never visible in "view source", although it is there in the page..?
What is the rule/good practice for dealing with html added after the document.ready?
So now there is a new element in this "virtual DOM" :
<form id="upload" method="post" action="other_script.php" enctype="multipart/form-data">
<div id="drop">
DROP HERE <small>Image .png or .jpg</small>
<a class="btn mr_button">Browse</a>
<input type="file" name="upl" />
</div>
<ul id="mr_uploaded_files_ul">
<!-- The global progress bar -->
<div id="progress" class="progress">
<div class="progress-bar progress-bar-success"></div>
</div>
<!-- The file uploads will be shown here -->
</ul>
</form>
And when I try to act upon this "invisible" part of the DOM :
$('#drop a').click(function(){
alert('Nope. Nothing');
});
Only when I
$(document).on('click', '#drop a', function() {
alert('Ah, this works');
});
But I need more than an alert. The whole $('#upload').fileupload({ ... })
callback suite is not executed, probably because of this DOM "existence" issue. BTW I use this very implementation in other pages, on plain existing DOM, and it works.
How can I act upon those newly-spawned DOM elements?
Add a callback function to your load
call, and then initialize your form.
$('#details div').html(ajax_spinner).load(script.php, "parameters", function() {
$('#upload').fileupload({ ... });
});
When you use a jQuery selector, like $('#upload'), those elements have to already exist. The upload form doesn't exist until after it's been loaded, so that selector returns empty until after the load finishes.
The reason the alert works
$(document).on('click', '#drop a', function() {
alert('Ah, this works');
});
is due to event delegation. Read more here: http://learn.jquery.com/events/event-delegation/