Elementor’s Accordion widget is a fantastic way to display content dynamically, but what if you want to link directly to a specific accordion item? You can do that by using URL hashes, which allow you to jump directly to an accordion panel. However, in some cases—such as when your site includes query parameters for tools like Google Tag Manager (GTM)—you may run into issues where the hash gets appended incorrectly, preventing the accordion from functioning as expected.
In this article, we’ll explain how to handle accordion behavior with URL hashes while ensuring it works properly even when query parameters are present.
Why Use URL Hashes for Accordions?
Adding a URL hash (like #accordion-1) to the end of a URL lets you direct users to a specific part of a page. When using Elementor’s Accordion widget, this is especially useful because you can link directly to a specific accordion item.
For example:
https://yourwebsite.com/faq#accordion-item-1
But, what if your website uses tools like Google Tag Manager or other services that automatically append query parameters to URLs? These query parameters can cause issues with the hash functionality, preventing the accordion from opening properly.
The Problem with Query Parameters
When query parameters like ?gtm=tracking-code are added to the URL, the hash that is supposed to trigger the accordion may get appended incorrectly, or not work as intended. This can result in a simple scroll to the accordion but without the proper open/close functionality.
To fix this, we need a custom script that:
- Ensures the accordion opens based on the URL hash.
- Works even when there are query parameters in the URL.
Solution: Custom Script for Accordion Behavior with URL Hashes
The following jQuery-based script solves this problem by extracting the hash from the URL and ensuring that the correct accordion item opens, regardless of any query parameters.
<script>
jQuery(document).ready(function($) {
// Function to extract the hash, even when query parameters exist
function getHashFromUrl() {
var url = window.location.href;
var hashIndex = url.indexOf('#');
return hashIndex !== -1 ? url.substring(hashIndex) : ''; // Return hash if present
}
var hash = getHashFromUrl();
if (hash !== '') {
var accordionItem = $(hash);
if (accordionItem.length > 0) {
// Close the first accordion if it has the 'open' attribute
var firstAccordionItem = $('.e-n-accordion-item[open]').first();
if (firstAccordionItem.length > 0) {
firstAccordionItem.removeAttr('open'); // Remove the 'open' attribute to close it
firstAccordionItem.find('.e-n-accordion-item-title').attr('aria-expanded', 'false'); // Update aria-expanded to false
}
// Open the targeted accordion by adding the 'open' attribute
accordionItem.attr('open', '');
accordionItem.find('.e-n-accordion-item-title').attr('aria-expanded', 'true'); // Update aria-expanded to true
// Scroll to the accordion with a 100px top offset once the page fully loads
$(window).on('load', function() {
$('html, body').animate({
scrollTop: accordionItem.offset().top - 100 // Subtract 100px for the offset
}, 500);
});
}
}
// Update the hash in the URL and aria-expanded when an accordion is clicked
$('.e-n-accordion .e-n-accordion-item-title').on('click', function() {
var clickedItem = $(this).closest('.e-n-accordion-item').attr('id');
if (clickedItem) {
window.location.hash = clickedItem;
// Toggle aria-expanded based on the click event
var isExpanded = $(this).attr('aria-expanded') === 'true';
$(this).attr('aria-expanded', !isExpanded ? 'true' : 'false');
}
});
// Prevent the default hash scrolling on page load
if (hash !== '') {
window.scrollTo(0, 0); // Scroll to top on page load to prevent default hash scroll
}
});
</script>
How the Script Works:
- Extracting the Hash:
The functiongetHashFromUrl()extracts the hash from the URL, even when there are query parameters like GTM tracking codes. This ensures that the script recognizes the correct part of the URL after the hash. - Opening the Accordion:
Once the hash is detected, the script opens the corresponding accordion by adding theopenattribute and setting thearia-expandedvalue totrue, making sure the accordion behaves as expected. - Handling Scrolling:
The script ensures that the page scrolls to the accordion smoothly with a 100px offset from the top. This prevents issues where the accordion is hidden behind sticky headers. - Preventing Default Browser Behavior:
To prevent the browser from scrolling to the top or other random locations after the page fully loads, the script overrides the default hash-based scroll behavior, ensuring the custom scroll is applied properly.
How to Add This Script to Your Website
Once you’ve got the custom script ready to control your Elementor accordion based on URL hashes, you’ll need to add it to your website. Below are a few different methods you can use, depending on your website setup and how you manage scripts.
1. Using an HTML Widget in Elementor
If you’re already using Elementor, you can easily add this script directly within your Elementor layout using the HTML widget. Here’s how:
Steps:
- Open the page where you’re using the Elementor Accordion.
- Add an HTML widget from the Elementor panel.
- Paste the entire script inside the HTML widget.
- Save the page.
This method is particularly useful if you only need the script to run on a specific page that contains the accordion. Elementor’s HTML widget allows you to add custom code that gets executed only when that page is loaded, ensuring that the script won’t affect other parts of your website.
2. Adding the Script to Your Theme’s Header or Footer
If you want the script to apply across multiple pages or even your entire website, you can add it to your theme’s header or footer. Here’s how to do it:
a. Adding via the Theme’s Customizer (No Coding Required)
Many WordPress themes provide a built-in option to add custom scripts through the Customizer. You can add the script to the footer of your website using this option.
Steps:
- Go to your WordPress dashboard and navigate to Appearance > Customize.
- Look for an option like Additional Scripts, Custom Code, or Footer Code (the exact name may vary depending on your theme).
- Paste the script inside the provided box (usually for Footer scripts).
- Publish the changes.
This will load the script site-wide in the footer, ensuring that it runs wherever your accordion widget is placed.
b. Manually Adding to the header.php or footer.php File
If your theme doesn’t have a built-in customizer option for adding scripts, you can manually add the script by editing the theme files.
Steps:
- Navigate to Appearance > Theme Editor in your WordPress dashboard.
- Choose the
header.phporfooter.phpfile (footer is preferred for this type of script). - Add the following code before the closing
</body>tag:
<script> // Paste the entire script here </script>
Save the changes.
This method ensures that the script is loaded globally across your site and is perfect for situations where your accordion may be used in different locations.
3. Using a Custom Code Plugin (Easy and Safe)
If you’re not comfortable editing your theme files directly, you can use a plugin to add custom code to your website without touching any code manually.
Some popular plugins for adding custom scripts are:
- Header and Footer Scripts: A lightweight plugin that lets you insert custom JavaScript or CSS into your website’s header or footer.
- WPCode (formerly Insert Headers and Footers): A powerful plugin that allows you to insert code snippets in your site’s header or footer.
Steps (using WPCode):
- Install and activate the WPCode plugin from the WordPress repository.
- Go to Code Snippets > Header & Footer in your WordPress dashboard.
- Paste your script into the Footer Scripts box.
- Save the changes.
This method is ideal for users who want a simple and safe way to add custom scripts without directly modifying theme files.
4. Adding to a Child Theme (Advanced Users)
For advanced users or developers, adding the script to a child theme is another great option. This ensures that your changes are not overwritten when the theme is updated.
Steps:
- First, ensure you have a child theme set up.
- Add the script to your child theme’s
functions.phpfile like this:
function custom_accordion_script() {
?>
<script>
// Paste your entire script here
</script>
<?php
}
add_action('wp_footer', 'custom_accordion_script');
Save the functions.php file.
By using a child theme, you ensure that your changes will persist even after updating the parent theme. This method is best for developers or users familiar with theme customization.