I have a custom template setup for the paragraph module in Drupal 8. It so the user can add an accordion to the body copy if wanted. I have an accessible code snippet that I have written and use whenever I need accordions. It works fine except when I use it normally, its on a custom coded page so I can change the ID value on each one. As this will be a paragraph module that the user adds to the page as many time as the like, I need to somehow dynamically apply the ID numbers to the snippet - adding 1 to the number every time the user adds another accordion.
So below is the code that I use:
<div class="accord">
<h2 class="toggleAccord">
<button aria-controls="accord-1" aria-expanded="false">{{content.field_accordion_title}}</button>
</h2>
<div class="accordion-text" aria-hidden="true" id="accord-1">
{{content.field_accordion_body}}
</div>
</div>
<script>
$(document).ready(function() {
openAccordion();
$(".toggleAccord button").click(function() {
var btn = $(this);
var toggle = btn.parent();
var content = btn.parent().next();
if (btn.attr('aria-expanded') === 'false') {
// open
$(content).slideDown();
toggle.addClass('closeAccord');
btn.attr('aria-expanded', 'true');
content.attr('aria-hidden', 'false');
} else {
// close
$(content).slideUp();
toggle.removeClass('closeAccord');
btn.attr('aria-expanded', 'false');
content.attr('aria-hidden', 'true');
}
});
});
</script>
So I need the 'accord-1' to dynamically count up one every time an accordion is added. accord-2, accord-3 etc.
Is there a way I can replace the number with a php or jQuery variable so it automatically counts up?
Yes you can count the DOM elements first. Then after counting and stocking this value in a variable, I would use ajax or xhr request to send this information to a php variable in my drupal side. Do you think you need a code suggestion to this?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.