jQuery Mobile - Dynamic Collapsible



Description

Collapsible can be added to a collapsible set dynamically.

Example

Following example demonstrates the use of dynamic collapsible in jQuery Mobile.

<!DOCTYPE html>
<html>
   <head>
      <title>Dynamic collapsible</title>
      <meta name = "viewport" content = "width = device-width, initial-scale = 1">
      <link rel = "stylesheet" href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
      <script src = "https://code.jquery.com/jquery-1.11.3.min.js"></script>
      <script src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
   </head>

   <body>
      <button type = "button" data-icon = "plus" data-iconpos = "right" data-mini = "true" 
         data-inline = "true" id = "add_collapsible">Add collapsible</button>
      <button type = "button" data-icon = "carat-d" data-iconpos = "right" data-mini = "true" 
         data-inline = "true" id = "expand_last">Expand last collapsible</button>
      <button type = "button" data-icon = "carat-u" data-iconpos = "right" data-mini = "true" 
         data-inline = "true" id = "collapse_last">Collapse last</button>
         
      <div data-role = "collapsibleset" data-content-theme = "a" data-iconpos = "right" id = "set">
         <div data-role = "collapsible" id = "set1" data-collapsed = "true">
            <h3>Heading 1</h3>
            <p>Hi!! This is collapsible content.</p>
         </div>
      </div>
      
      <script>
         $( document ).on( "pagecreate", function() {
            var nextId  =  1;
            $("#add_collapsible").click(function() {
               nextId++;
               var content  =  "<div data-role = 'collapsible' id = 'set" + nextId + "'>
                  <h3>Heading " + nextId + "</h3>
                  <p>Hi!! This is collapsible content.</p></div>";
               $( "#set" ).append( content ).collapsibleset( "refresh" );
            });
            
            $( "#expand_last" ).click(function() {
               $("#set").children(":last").collapsible( "expand" );
            });
            
            $( "#collapse_last" ).click(function() {
               $( "#set" ).children( ":last" ).collapsible( "collapse" );
            });
         });
      </script>
   </body>
</html>

Output

Let's carry out the following steps to see how the above code works −

  • Save the above html code as dynamic_collapsible.html file in your server root folder.

  • Open this HTML file as http://localhost/dynamic_collapsible.html and the following output will be displayed.

jquery_mobile_widgets.htm
Advertisements