$('div#Settings ul li').click(function () {
var url, template;
var self = $(this);
if (!$(self).hasClass('selected')) {
var ContextMenu = CreateContext($(self));
var id = $(self).attr('id');
etc…
function CreateContext(item) {
var ContextMenu = $('div#ContextMenu');
if (!$(ContextMenu).length) {
$('<div id="ContextMenu"></div>').appendTo('body');
CreateContext(item);
}
$(ContextMenu).slideUp(150, 'swing', function () {
$(ContextMenu).insertAfter(item);
});
$(item).addClass('selected').siblings().removeClass('selected');
return $(ContextMenu);
}
On the first call to CreateContext(item) I cannot use the variable ContextMenu later in the .click code. However, if CreateContext is called twice, everything works fine. I am getting an undefined variable when i console.log(ContextMenu) the first time. The second time it gets the object correctly. How can I fix this? Thanks.
That’s because
div#ContextMenudoesn’t exist the first time you call CreateContext. In fact your function detects that condition and then creates it. But, after creating it, you don’t populate the value ofContextMenuinside your function so the rest of the function doesn’t work properly.Here’s what I would suggest:
Note, once
ContextMenuis a jQuery object, you don’t have to surround it with$()after that as it’s already a jQuery object.