Reputation: 1587
I'm learning jQuery and I have got following problem. In my code I have got variable prev_content
and I want display content of that variable in new .dialog()
. Variable is defined globally, then content is set in .click()
function, but variable returning UNDEFINED
$('body').append('<div class="ui-dialog" id="jp_main_menu"><ul id="jp_templates_list"></ul></div>'); console.debug(jp_console_title + "[OK] #jp_main_menu - creating element");
JPTemplateGetList();
var prev_content;
$(".jp_show_preview_window").click(function(){
prev_content = jp_tpl[$(this).attr("id")].source;
$('#jp_preview_window').dialog("open");
return false;
});
$('#jp_main_menu').dialog({
autoOpen: false,
modal: false,
resizable: true,
draggable: true,
position: ['center',100],
title: "MY WINDOW",
width: 600
}); console.debug(jp_console_title + "[OK] #jp_main_menu - setting jQuery .dialog function");
$('body').append('<div class="ui-dialog" id="jp_preview_window">'+ prev_content +'</div>');
As you can see, variable content is set on line:
prev_content = jp_tpl[$(this).attr("id")].source;
But when I wanna display that content (last line of my code), it will show UNDEFINED
.
Can you help me please? Thanks
Upvotes: 0
Views: 60
Reputation: 707158
This is a matter of timing. Your last line of code runs BEFORE you trigger the click handler, thus your variable is still undefined
as the code to set it has not been called yet (it isn't called until the mouse click happens).
Move the last line to be inside the click handler:
$('body').append('<div class="ui-dialog" id="jp_main_menu"><ul id="jp_templates_list"></ul></div>'); console.debug(jp_console_title + "[OK] #jp_main_menu - creating element");
JPTemplateGetList();
$(".jp_show_preview_window").click(function(){
var prev_content = jp_tpl[$(this).attr("id")].source;
$('body').append('<div class="ui-dialog" id="jp_preview_window">'+ prev_content +'</div>');
$('#jp_preview_window').dialog("open");
return false;
});
$('#jp_main_menu').dialog({
autoOpen: false,
modal: false,
resizable: true,
draggable: true,
position: ['center',100],
title: "MY WINDOW",
width: 600
});
Upvotes: 2