Search code examples
javascriptjqueryjmenu

jquery need to delay call to plugin


I'm injecting the HTML for web page's header into the DOM via jquery (simulate a masterpage). In the header I load a jquery navigation menu plugin called jMenu. I am able to inject the HTML for the header and it appears no problem. After that loads, I need to make the jquery call to jMenu.

The problem is it looks like the jMenu call is being made before the DOM is finished updating and throws an error complaining it can't find one of the html elements. So I tried to delay loading to jMenu but I don't think the call is even getting executed now since my alerts aren't popping up. I've done some searching on this already but have not been able to get this to work. I'm guessing its a minor syntax thing. I tried a few things:

HTML:

<body>
<div class="mpheader"> 
    <div class="header"> <!-- start of injected html -->
    <br/><br/>
    <h1 style="text-align: center;">Reports</h1>
    <div class="centerControl">
        <ul id="jMenu">
        ...
    </div>               <!-- end of injected html -->
</div>

<div class="content">

    <h2>Welcome</h2>
    ...

JS:

$(document).ready(function () {

// Load Header
$.get( 
    "./header.jsp", 
    function(data) {
        $(".mpheader").html(data); 
    }
);

// Initialize Navigation Menu
$(".header").on("load", function() { /* doesn't get called */
    alert('called');
    $("#jMenu").jMenu();
})

$(".mpheader").on("load", function() { /* doesn't get called */
    alert('called');
    $("#jMenu").jMenu();
})

$(window).load(function(){   /* doesn't get called */
    alert('called');
    $("#jMenu").jMenu();        
})

//$("#jMenu").jMenu(); /* will cause error complaining about dom */

// TODO: Load Footer

});

Solution

  • Once your get returns, you are calling a function to fill the html of your header. You can just setup the menu after that. The following should work for you:

    $.get("./header.jsp", 
        function(data) {
            $(".mpheader").html(data);
            $("#jMenu").jMenu(); 
        }
    );