Jump to content

Open Accordion Block Using ID In Link

Go to solution Solved by PoochKingdom,

Recommended Posts

Posted (edited)

EDIT: See my later reply for an optimized version of this code.

I have seen a few questions about the possibility of using a link to open an accordion item automatically. I did a little experimenting myself, as I needed the same functionality. I've adopted this piece of code into the header of the page that has the accordion. In my case, I only have one accordion item I need to open so I used the Firefox developer tool to grab the id of the item, then reference it both in my javascript block and the link I'm opening:

E.g. My accordion id is called #button-block-yui_3_17_2_1_1717881226444_11132-1

In my case, the link on the calling page is going to be https://poochkingdom.com/faq#button-block-yui_3_17_2_1_1717881226444_11132-1, and the FAQ page opens with the accordion item open.

<!-- Put this in your page header, not the site header -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	<!-- If a location hash is passed to the window, and it's the one I'm looking for -->
	if (window.location.hash && window.location.hash === '#button-block-yui_3_17_2_1_1717881226444_11132-1'){
        <!-- Trigger the click event for this item so it opens on page load -->
		$(function(){
			$("#button-block-yui_3_17_2_1_1717881226444_11132-1").click();
		});
	}
});
</script>

You may need to customize it if you need to open more than one block by id, but hopefully this gives you the gist of how to make this work.

Let me know if you have any optimizations to this code that you can suggest, as I'm new to jScript.

Edited by PoochKingdom
I provided an optimized javascipt block in a later reply.
Link to comment
9 hours ago, PoochKingdom said:

I have seen a few questions about the possibility of using a link to open an accordion item automatically. I did a little experimenting myself, as I needed the same functionality. I've adopted this piece of code into the header of the page that has the accordion. In my case, I only have one accordion item I need to open so I used the Firefox developer tool to grab the id of the item, then reference it both in my javascript block and the link I'm opening:

E.g. My accordion id is called #button-block-yui_3_17_2_1_1717881226444_11132-1

In my case, the link on the calling page is going to be https://poochkingdom.com/faq#button-block-yui_3_17_2_1_1717881226444_11132-1, and the FAQ page opens with the accordion item open.

<!-- Put this in your page header, not the site header -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	<!-- If a location hash is passed to the window, and it's the one I'm looking for -->
	if (window.location.hash && window.location.hash === '#button-block-yui_3_17_2_1_1717881226444_11132-1'){
        <!-- Trigger the click event for this item so it opens on page load -->
		$(function(){
			$("#button-block-yui_3_17_2_1_1717881226444_11132-1").click();
		});
	}
});
</script>

You may need to customize it if you need to open more than one block by id, but hopefully this gives you the gist of how to make this work.

Let me know if you have any optimizations to this code that you can suggest, as I'm new to jScript.

Another approach we can try is adding the following changes on the DOM of accordion block:

- Adding the attribute [data-is-open = true] for .the class: accordion-items-container

- Add the class 'accordion-item__dropdown--open' for the class: accordion-item__dropdown

With this approach, we can open many items in your accordion at the same time, instead of applying only one item with your above code.

Hope that it is useful for you

BeyondSpace - Squarespace Website Developer

🖼️ Lightbox Studio (Enable Pinch/Zoom on lightbox, video lightbox and much more)
🗓️ Delivery Date Picker (Squarespace Date picker form field)
💫 Gallery block 7.1 workaround
🥳 No-code customisations for Squarespace (+100 Spark plugin customisations)
🥳 Freemium Squarespace Widget Templates (+1000 Elfsight Templates)

If you find my answer useful, let's leave a like or upvote so others with the same issue can find their solution. Thank you!

Link to comment

Thanks @Beyondspace 

The point of my solution was a specific scenario where I have a link on page X with a hash reference to an accordion on page Y, and I want the text to open for that particular item when I click the link on page X.

I'm sure that there's an optimization that can be made where you can index all the accordion items on page load, then use the window.location.hash to click the specific item.

Link to comment
  • Solution
Posted (edited)

Below is the optimized code. I decided to take a look at what I wrote and tested a couple of scenarios.

The accordion id syntax used by Squarespace for my pages is "button-block-yui-<some id>-0" for the first item, "button-block-yui-<some id>-1" for the second, etc.

If you want to create a link to open a specific accordion item, you'll use:
https://yoursite.com/page#<button-block-yui-dropdownNumber>, where the value of dropdownNumber is 0, 1, 2, 3, ..., depending on which item in the list you want to open.

Here's the optimized code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
	<!-- Save the window location hash passed to this page -->
	var loc = window.location.hash;
	<!-- If a hash exists, and there's a matching element in the page -->
	if (loc.length && $(loc).length){
		<!-- Execute the click event on the matching element -->
		$(loc).click();
	}
});
</script>
Edited by PoochKingdom
Typos
Link to comment
  • 2 months later...

Hey - @PoochKingdom this is so useful, thank you. Would you be willing to help me figure out what I'm doing wrong implementing it?

On this page

https://www.careful.industries/test-braid-accordions

I have 4 x accordions, each with 5 items. I would like to create links which when clicked, scroll to the relevant accordion heading/button/content dropdown, and open that accordion content dropdown. I'm OK if they stay open once the link is clicked, but if another is clicked, I'd like the page to jump to the new location and open the accordion content. (So, many accordion content items open at once is OK).

I have a floating menu set up, where I've found the #button-block-e4217f562264d4a2c827-0 to -4 IDs for the first accordion on the page. I have plugged in the jQuery code above in to the footer.

I've got the # links jumping to the relevant accordion <li> item anchor by id. (nb not all accordions are currently linked up), but not opening the related accordion content.

You can see at the side where I've found selector path IDs for the various elements of the first accordion block, and none of those work to open the accordion content, either. For reference:

Streets Accordion:
content block #yui_3_17_2_1_1725290636637_551
ul #yui_3_17_2_1_1725290636637_550
li  #yui_3_17_2_1_1725290636637_549
h3 #yui_3_17_2_1_1725290636637_548
button #button-block-e4217f562264d4a2c827-0 et seq
title span #yui_3_17_2_1_1725290636637_547
content dropdown #dropdown-block-e4217f562264d4a2c827-0 et seq

What am I doing wrong? Sadly my js is very limited, this is right at the ends of my ability to fix, and I can't work out how to use dev tools in my browser to debug. I kind of understand some of the words in @Beyondspace's reply, but definitely couldn't write js based on it, sorry.

Your help would be most appreciated.

Link to comment

Just an update to say - a friend with JS chops wrote me a tiny JS script to achieve this. Popping it here in case it's useful to anyone. It's well commented, and targets the button-block ID. Console logging currently on. Seems to work, but not extensively tested across browser.

 <script>
    // This will click the button if it's not already open
    const openButton = (id) => {
      console.log('>>>>>>>>>> ', id)
      // Try and grab the button by its ID
      const button = document.getElementById(id)
      console.log(button)
      // If the button doesn't exist, do nothing
      if (!button) return;
      // Click the button if 'aria-expanded' is 'false'
      if (button.getAttribute('aria-expanded') === 'false') {
        button.click();
        // Scroll the button into view
        button.scrollIntoView({ behavior: 'smooth', block: 'start' });
        // Now we want to update the URL to add # and the button ID to the end of the current URL (replacing any existing hash)
        // So people can still link directly to the accordion
        // Update the URL with the button ID
        const newUrl = window.location.href.split('#')[0] + '#' + id;
        history.pushState(null, '', newUrl);
      }
    }

    // Once the document is loaded, we want to add an event listener to all links that have an href that contains '#button-block-'
    // This will grab all the links that link to accordions, and ignore the ones that don't
    document.addEventListener('DOMContentLoaded', function () {
      // Grab all the links that link to accordions
      const links = document.querySelectorAll('a[href*="#button-block-"]');
      // Add an event listener to each link
      links.forEach(link => {
        link.addEventListener('click', function (event) {
          // Stop the link from doing its default action
          event.preventDefault();
          // Get the button ID from the link
          const buttonId = link.getAttribute('href').split('#')[1];
          // Open the button
          openButton(buttonId);
        });
      });

      // Finally, if there's a hash in the URL, open the button if it isn't already open
      const hash = window.location.hash;
      if (hash) {
        setTimeout(() => {
          openButton(hash.split('#')[1]);
        }, 666);
      }
    });
  </script>

 

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

×
×
  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.