Wednesday 12 June 2013

Javascript, Load file (html script) into div, getting back UI reference

Load UI dynamically with jquery's .load() function
Hi, bellow is a javascript  script where loads another html into your page, into another div or whatever. As you see, creates another div with a new provided id. This script is useful because applies the "hooks" when the load is completed, so there is no case to loose the load. Also, the function that it offered to be called after the load is completed, returns a lot of args, like the "xhr" where is the real load where the jquery uses under the hood.

function LoadUIFromFile(
    HostID,            // The id of the element where the new element will be added.
    EmbeddedID,        // The id of the new embedded div element.
    FileToLoad,        // The html script where will be loaded in the new id.
    HideIt,            // (optional) Boolean, hide it or not on new div's creation.
    OnLoad,            // (optional) Function will be called on load completion. Available args: Caller, responseText, textStatus, xhr.
    CallerObject    // (optional) Which object called this function, this will be used for OnLoad
){

    //handle the undefined variables
    if (typeof HideIt == 'undefined') HideIt=true;
    if (typeof OnLoad == 'undefined') OnLoad=null;
    if (typeof CallerObject == 'undefined') CallerObject=null;
   
    //create the div, load the data of the file to it and hide it
    $("#"+HostID).append('<div id="'+EmbeddedID+'"></div>');
    $("#"+EmbeddedID).data("AnelUtils_OnLoadFunction",OnLoad);
    $("#"+EmbeddedID).data("AnelUtils_CallerObject",CallerObject);
    $("#"+EmbeddedID).load(FileToLoad, null, function(responseText, textStatus, xhr) {
        if ($(this).data("AnelUtils_OnLoadFunction")!=null)
            $(this).data("AnelUtils_OnLoadFunction")($(this).data("AnelUtils_CallerObject"), responseText, textStatus, xhr);
    });
    if (HideIt) $("#"+EmbeddedID).hide();
   
    return $("#"+EmbeddedID);

}

No comments:

Post a Comment