Using JSLink in SharePoint to build an accordion displaying FAQs
Muawiyah Shannak launched excellent JSLink code samples. One example covers FAQs displayed in an accordion like structure. The example works perfect with "single line of text" columns. The accordion fails using "multiple line of text - Enhanced rich text".
Searching the internet for solutions I found two articles covering this issue:
- Using $(description).html to cast the string, where description is the answer of our FAQs. This solution works with plain text but the accordion fails, if text is marked as bold for example.
- The other solution works quite well, even with Enhanced Rich Text, but the accordion has some kind of flickering.
I finally developed the following code. Only two lines of JQuery code & easy to understand.
-
Just use Muawiyah Shannak's code and replace the OnPostRender method and the accordion Template.
-
If you prefer a faster toogling effect, use "fast" instead of "slow".
-
Place the tag 'style="display:none"' into a separate css file to get the code cleaner. I put it into the JSLink file to get the example work without an additional css file. The style tag ensures that the accordion is displayed in a collapsed manner, when the page is rendered.
function accordionTemplate(ctx) { var title = ctx.CurrentItem["Title"]; var description = ctx.CurrentItem["Description"]; return "<div class=\"accordion-toggle\"><h2> " + title + "</div></h2><div class=\"accordion-content\" style=\"display: none;\">" + description + "</div>"; } function accordionOnPostRender() { $('.accordion-toggle').click(function () { $(this).next().slideToggle('slow'); $(".accordion-content").not($(this).next()).slideUp('slow'); });