Javascript global variable does not work in jQuery Droppable

advertisements

This must be some exception as I'm pretty sure it should work:

var myvar; // global variable

function draggableinit(e, ui){
    console.log(myvar); // still defined here
    jQuery('.drop-div').droppable({
        deactivate: function(event, ui){
            console.log(myvar); // why undefined?
        }
    });
}

function set(){
    var myvar = jQuery('.cont').resizable({
        start: function(event, ui) {  },
        resize: function(event, ui) {  },
        stop: function(event, ui) { // functions to manipulate size  }
    });
    return myvar;
}

jQuery(document).ready(function(){
    myvar = set();
    jQuery('.some-div').draggable({
        "start": draggableinit
    });
});

I'm wondering why myvar is undefined in that place? Shouldn't it be accessible from any place?

Documentation: http://jqueryui.com/draggable/


Assign it directly to window to rule out scope conflicts. That should work. Creating var foo outside of an intended scope doesn't automatically make it "global", just global to that scope block and nested scopes.

function draggableinit(e, ui){
    jQuery('.drop-div').droppable({
        deactivate: function(event, ui){
            console.log(window.myvar); // why undefined?
        }
    });
}

jQuery(document).ready(function(){
    window.myvar = 123;
    jQuery('.some-div').draggable({
        "start": draggableinit
    });
});