I am using jquery ui.
html :
<div id="dialog" style="border:1px solid green; width:150px; margin:auto;">
<br />
<div class="dialog_insider" style=" border:1px solid red; width:120px; margin:auto; display:none;">
this is dialog insider
</div><!-- end of id dialog_insider-->
<br />
</div>
javascript / jquery code snippet:
$(document).ready(function(){
//$(".dialog_insider", my_dialog).click(function(){
$(".dialog_insider").click(function(){
alert("this is an alert box");
});
$("#dialog").click(function(){
my_dialog= $(this).clone();
my_dialog.dialog();
$(".dialog_insider", my_dialog).css('display','block');
});
});
Clicking on the dialog box on ‘dialog_insider’ div no longer shows the alert box. To show it there I have to remove the following snippet
$(".dialog_insider").click(function(){
alert("this is an alert box");
});
and place it in the following way :
$("#dialog").click(function(){
my_dialog= $(this).clone();
my_dialog.dialog();
$(".dialog_insider", my_dialog).css('display','block');
$(".dialog_insider", my_dialog).click(function(){
alert("this is an alert box");
});
});
I know that much. My questions are:
-
What is the concept of context here that the former coding pattern won’t cover up the ‘dialog_insider’ div on the dialog box?
-
If the amount of code to be re-written to work in a different context is large, then is there any workaround so that i could easily make the code work in a different context without having to re-write all?
This is because you are creating a new element and inserting it into the DOM via clone(). The ‘click’ handler is not bound to dynamically created elements. You will need to switch to
.on( 'click', function() { ... } );and use delegated events (jQuery >=1.7)Here is an updated jsFiddle. Check out the documentation for the on() here.
Please note that you should