Search code examples
javascriptjqueryajaxjquery-ui-accordion

Ajax jQuery Accordion Show First 5 Elements On Page


What I would like to do is Ajax the top five accordion elements from a page. I'm having trouble keeping the existing content in accordion format after loading it via ajax. Would it be possible to just pull the top five using .load()? How should I go about this problem?

Page I would like to ajax from:

<div id="main" class="accordians">
    <h3>Collapsible Group Item #1</h3>
    <div>
        <p>This is section 1. Place your content here in paragraphs or use div elements etc.</p>
    </div>
    <h3>Collapsible Group Item #2</h3>
    <div>
        <p>This is section 2. Place your content here in paragraphs or use div elements etc.</p>
    </div>
    <h3>Collapsible Group Item #3</h3>
    <div>
        <p>This is section 3. Place your content here in paragraphs or use div elements etc.</p>
    </div>
    <h3>Collapsible Group Item #4</h3>
    <div>
        <p>This is section 4. Place your content here in paragraphs or use div elements etc.</p>
    </div>
    <h3>Collapsible Group Item #5</h3>
    <div>
        <p>This is section 5. Place your content here in paragraphs or use div elements etc.</p>
    </div>
    <h3>Collapsible Group Item #6</h3>
    <div>
        <p>This is section 6. Place your content here in paragraphs or use div elements etc.</p>
    </div>
</div>

Accordion Looks like the following

Second page will be pulling the accordian via Ajax:

<div id="load-top-five">#load top five accordions into here.</div>
<script>
   // would like to combine the functionality to only return the top five.
   $('#load-top-five').load('https://www.example.com #main'); // this loads the page but doesn't keep it in the correct format.
   $('#load-top-five').find('#main:lt(5)').each(function(){...} // I would like to do some logic like this to only render the top 5.
<script>

Solution

  • First, you will have to load the element onto the page. The accordion will only format after the data is done loading.

    $(function() {
        $('#load-into-new-accordion').load('https://www.someurl.com #accordion_data');
    });
    
    // create a function for the accordion.
    function loadAccordionFormating() {
      $('#load-into-new-accordion').accordion({});
    }
    
    // after the data is done loading apply the formatting.
    window.onload = function() {
       loadAccordionFormating();
    };
    

    To hide the elements you can use the ui-id-1, ui-id-2, etc which you just create a simple for loop.

    for(var i=1;i<15; i++) {
        $(`ui-id-${i}`).hide();
    }
    

    In addition, since this is slow you can also by default hide elements with css and just show them with the same method as above.