Search code examples
javascriptjqueryhtmlcssgumby-framework

HTML script .load preventing responsive elements


I'm using the gumby framework from here and everything seems to be going well. I would like to implement a mobile navigation list (where the links are grouped under a single button as detailed here).

This works fine with a normal HTML page, but as I have multiple pages with the same header (nav bar)/footer, I decided to put all the HTML for those in separate files, and load them with a script:

<script>
    // load navigation/footer
    $(function () {
        $("#navigation").load("html/nav.html");
        $("#footer").load("html/footer.html");
    });
</script>

The problem is when I do this, my mobile navigation list does not work (as if the mobile nav bar is being initialized, then the document loads the HTML resulting in no hooks). I hope there's a simple fix for this. Any ideas?

Thanks.


Solution

  • When you say

    preventing responsive elements

    Do you mean, event handlers and the like are not bound to the new HTML that has been loaded ?


    One way is to set delegated event handlers

    $(document).on('click','.mylaterloadedanchors', function() { ... 
    

    But this is quite overkill to have too many of these.


    Another, looking into controlling the bindings into a function that you can call after templates/DOM partials have loaded.

    • load templates
    • set handlers of the template.

    Say,

    var app = function() { 
    
        .. list all listeners etc
        };
    
    /* load templates using the callback jq provides for .load() 
       and trigger the app containing the listeners*/
    
    $('#navigation').load('html/nav.html', app);
    

    Another way is to have your nav.html js bindings src'd from the nav.html page itself.

    Not a bad idea when managing 'views' - eg

    nav.html ships with nav.js etc ..

    views with viewmodels and viewbindings