Search code examples
htmljquery-mobileexternaljquery-mobile-collapsible

Updating a DIV inside a Collapsible in JQuery Mobile only when the Collapsible is opened (eg. load on demand)


I'm trying to execute a call to an external program to create content in a DIV inside a collapsible in JQuery Mobile, to have some code run when a div in a JQM collapsible appears when the collapsible is opened. I'm trying to use the jquery.appear plugin (https://github.com/morr/jquery.appear) as follows:

<div id="coll2" data-role="collapsible" data-mini="true" data-inset="false" data-iconpos="right">
  <h1>Collapsible 1</h1>
  Collapsible Title! 
  <div id="2wrapper"></div>
</div>

<script type="text/javascript">

$(document.body).on('appear', '#2wrapper', function() {
  // this element is now inside browser viewport

    alert("Script running");
    $("#2wrapper").load('some-external-program-content.cgi');

});

</script>

I'm obviously missing something because the div isn't updating when the collapsible is opened. Would appear work in this instance? Or is there a more effective way to achieve this "on demand" loading of the content in the collapsible?


Solution

  • You don't need any plugin, just use the expand event on the collapsible:

    $(document).on("collapsibleexpand", "#coll2", function(event, ui)
    {
        $("#2wrapper").load('some-external-program-content.cgi');
    });
    

    ...By the way: it's good practice to avoid having IDs starting with a number (even if it's permitted in HTML5).