0

I am needing to create an accordion in SharePoint web part for online, however I am quiet new to JS & Jquery.

Is there an example of an accordion that I can use to help this?

The items must be referencing the SP list & items inside.

A little guidance will be grateful! Thanks

1

You can use jQuery UI accordion and get the items using REST API as shown below:

<html>
<head>

<script src="/_layouts/15/sp.runtime.js" type="text/javascript"></script>
<script src="/_layouts/15/sp.js" type="text/javascript"></script>

  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> 

<script type="text/javascript">  
$(document).ready(function(){  
GetItems();
});
function GetItems(){
var siteURL = _spPageContextInfo.webServerRelativeUrl;
    $.ajax({
            url: siteURL + "/_api/web/lists/GetByTitle('Loyalty%20Rewards')/items",   //change the list name
            type: "GET",
            dataType: "json",
            headers: {
            Accept: "application/json;odata=verbose"
            },
        success: function(data) {
         if (data.d.results.length > 0) 
           {
            $('#accordion').append(GenerateAccordionFromJson(data.d.results));  
            $( "#accordion" ).accordion();
           }
         else{  
            $('#accordion').append("<span>No Records Found.</span>");  
            }
        },
        error: function(error){
            alert(JSON.stringify(error));
        }  
    });
}  
function GenerateAccordionFromJson(objArray) 
    {  
    var accordionContent = "";
    for (var i = 0; i < objArray.length; i++) 
    {  
        accordionContent += '<h3>' + objArray[i].Title + '</h3>';               
               //change the column name
        accordionContent += '<div><p>' + objArray[i].Description + '</p></div>';           //change the column name
    }
    return accordionContent;
    }


</script>  
</head>
<body>
<div id="accordion">
</div>
</body>
</html>

Above code is tested and works well, all you need to is change the list title and the column name from where you want to show the data.

Reference: jQuery UI Accordion

  • Thanks! But how would the items inside the accordion be referenced from the SP list? As this needs to display the information – Danielle Sutton Sep 24 '18 at 12:28
  • I have changed the code that binds the list data (using REST API) dynamically in accordion. – Sohail Shaikh Sep 25 '18 at 4:43
  • Hi I have tried to use your code and updated the list name and column name but i got an error when loading this on the page – Danielle Sutton Sep 25 '18 at 18:04
  • Please tell me what error you get so that I can help you further. – Sohail Shaikh Sep 26 '18 at 4:34
  • {"readyState":4,"responseText":"{\"error\":{\"code\":\"-1, System.ArgumentException\",\"message\":{\"lang\":\"en-US\",\"value\":\"List 'Upcoming COPs' does not exist at site with URL 'bp365.sharepoint.com'.\"}}}","responseJSON":{"error":{"code":"-1, System.ArgumentException","message":{"lang":"en-US","value":"List 'Upcoming COPs' does not exist at site with URL 'bp365.sharepoint.com'."}}},"status":404,"statusText":"error"} – Danielle Sutton Sep 26 '18 at 9:25
0

If you want to show list items as accordion in list view, we can use JSLINK to achieve it. The following code for your reference. Create a custom list and add "Description" column into this list, then add the code below into a script editor web part in list view.

<script type="text/javascript">
(function () { 

    // jQuery library is required in this sample 
    // Fallback to loading jQuery from a CDN path if the local is unavailable 
    (window.jQuery || document.write('<script src="//ajax.aspnetcdn.com/ajax/jquery/jquery-1.10.0.min.js"><\/script>')); 

    // Create object that have the context information about the field that we want to change it's output render  
    var accordionContext = {}; 
    accordionContext.Templates = {}; 

    // Be careful when add the header for the template, because it's will break the default list view render 
    accordionContext.Templates.Header = "<div class='accordion'>"; 
    accordionContext.Templates.Footer = "</div>"; 

    // Add OnPostRender event handler to add accordion click events and style 
    accordionContext.OnPostRender = accordionOnPostRender; 

    // This line of code tell TemplateManager that we want to change all HTML for item row render 
    accordionContext.Templates.Item = accordionTemplate; 

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(accordionContext); 

})(); 

// This function provides the rendering logic 
function accordionTemplate(ctx) { 
    var title = ctx.CurrentItem["Title"]; 
    var description = ctx.CurrentItem["Description"]; 

    // Return whole item html 
    return "<h2>" + title + "</h2><div>" + description + "</div><br/>"; 
} 

function accordionOnPostRender() { 

    // Register event to collapse and uncollapse when click on accordion header 
    $('.accordion h2').click(function () { 
        $(this).next().slideToggle(); 
    }).next().hide(); 

    $('.accordion h2').css('cursor', 'pointer'); 
}
</script>

If you want to build accordion base on the list items in a client web part, we need using REST API to get the list data and build the accordion using jQuery.

  • HI I have tried to add your JS file. I updated the fields, uploaded the file to site assets library, added the list to the page and referanced the file and this still hasnt worked. I didnt see anything change within the list. – Danielle Sutton Sep 25 '18 at 18:02
  • Did you try to add the code into a script editor web part in list view. – LZ_MSFT Sep 26 '18 at 1:02
  • As in the miscellaneous part of the list webpart under the JS link? This is where i was referencing the script. Or are you speaking about a different way to load the script editor into the list? Is this in the list itself? – Danielle Sutton Sep 26 '18 at 9:29
  • @LZ_MSFT , using the Sohail's solution, how to create the sections -- say am having a "category1" section as a first title of accordion with column1, column2 of splist are listed and then category2 as second section title under which column3, column4 of splist are listed – userAZLogicApps Apr 3 at 16:52
  • @sohail - how to create a category if the names are different - say, i have a category called Admin --its a section name --with column3, column4 ,column5 are present. section names are just labels and not columns/fields of the splist. – userAZLogicApps Apr 3 at 16:57
0

Not sure if you've explored a more OOB option, but possibly using the 'Group By' setting in a new view would work? This styling option for a view allows for an collapsible accordion feature; however, you must choose a column upon which the items are grouped (which ends up being displayed as the heading for each group).

enter image description here

Cheers

  • There's a difference between accordion and group by. Accordion displays content of only one category at a time. Group by can display contents of various category at a time. – Sohail Shaikh Oct 19 '18 at 17:58
  • Sure but I don't think that means it couldn't be a viable solution for what Danielle is looking to accomplish, based on how she described it. – Drew Paxton Oct 19 '18 at 18:02
0

I just implemented this option for an FAQ list and it worked like magic. The key is to create the JS file and then when you add the webpart to a new page add the link in the JSlink of the webpart.

(function () {

    var overrideCurrentContext = {};
    overrideCurrentContext.Templates = {};

    overrideCurrentContext.Templates.Header = "<div class='ListAccordion'>";
    overrideCurrentContext.Templates.Footer = "</div>";

    overrideCurrentContext.OnPostRender = OnPostRender;
    overrideCurrentContext.Templates.Item = ItemTemplate;

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideCurrentContext);

})();



function ItemTemplate(ctx) {
    var Question  = ctx.CurrentItem["Question"];
    var Answer = ctx.CurrentItem["Answer"];

    return "<h2>" + Question + "</h2><p>" + Answer + "</p><br/>";
    }

function OnPostRender() {

    $('.ListAccordion h2').click(function () {
        $(this).next().slideToggle();
    }).next().hide();

    $('.ListAccordion h2').css({
    "background-color": "grey", 
    "cursor": "pointer", 
    "color": "white" ,
    "border-radius" : "15px",
    "padding-left" : "10px"
    });
}

I got the instructions from this link https://www.c-sharpcorner.com/article/implement-accordion-in-sharepoint-using-js-link-and-client-side-rendering/

Hope this gets you closer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.