I have a page with a div tag that I load different views into using jQuery .load()
<div class="main-content">
<div id="load"></div>
</div>
When I load different views like the following, I can't access any of the elements from settings.html
$("#settings").click(function(){
$("#load").load("main/settings.html");
//not working
$("#test1").click(function(){
alert('hello');
});
});
According to the second answer in this post:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call...
So I moved my .click()
code to the page that was being loaded (settings.html in this case) and I can access the elements from settings.html. Or I can do the suggested similar code posted
$("#settings").click(function(){
$("#load").load("main/settings.html", function(){
$("#test1").click(function(){
alert('hello');
});
});
});
//or
$("#settings").click(function(){
$("#load").load("main/settings.html");
$(document).on("click","#test1",function(event){
alert('hello');
});
});
But I'd like to know how to bind all the elements assuming I don't know which ones ahead of time. In the above examples I know I need to bind #test1
id. But if I have a file like play.js
where I'm changing different things on a loaded page, the methods listed above will require that I separate my code from play.js
and put each piece in a function tied to the load event. I have lots of .load()
events and wanted to keep my js like .click()
etc in a separate file.
How do I bind all elements that are loaded without specifying them ahead of time? Or how do I tell jQuery to perform something like:
$("#settings").click(function(){
$("#load").load("main/settings.html", function(){
// pseudo code
(function(){
bind all elements from main/settings.html to DOM
});
});
});
So the scripts listed after it like this can access thoese elements.
<script src="../js/play.js"></script>