In the Bricks Facebook group, a user asks:
How can I make the nestable accordion first entry open on desktop but closed on mobile?
Here’s a way to do it using a bit of custom JavaScript.
First select your Accordion (Nestable) element in the builder and toggle “Expand first item” on.
Edit your Page/Template with Bricks.
Click on Settings (gear icon) → PAGE SETTINGS → CUSTOM CODE. Add this under Body (footer) scripts:
<script>
document.addEventListener('DOMContentLoaded', function() {
// Specifically for mobile, check if the first item is open and close it
if (window.innerWidth <= 768) { // Adjust as needed for your mobile breakpoint
const firstContent = document.querySelector('#brxe-nmcaww .brxe-block.listening:first-child .accordion-content-wrapper');
if (firstContent) {
firstContent.style.display = 'none';
}
}
});
</script>
Replace #brxe-nmcaww
with the HTML selector of your Accordion (Nestable) element.
Note: This only works after a page refresh 768px and below. You can’t see it take effect if you are resizing the window down from desktop to mobile.
5 comments
Simon
I can't get it to work. I'm trying to make it work in a Bricks template. I copied the code and pasted it into the Page Settings --> custom code --> header scripts. Ofcourse I replaced the #brxe-nmcaww with my own.
What am I doing wrong?
Sridhar Katakam
Just tested and works fine here.
Make sure the HTML ID is indeed present in the DOM on the front end for your nestable accordion.
Also, the code should be added under Body (footer) scripts. I've updated the post to inform the same.
Simon Giaccotto
Great!! Now it works 🙂 It was the body(footer) part.
Patrik
Hi!
And how modify the code, if I want to open ALL accordions in desktop and closed on mobile. 🙂
Thanks you help!
Sridhar Katakam
Hey Patrik, you could use the new conditional accordion feature of our BricksExtras' Pro Accordion element for this w/o writing any code.
See near the bottom of https://bricksextras.com/docs/pro-accordion/.