Open a Particular Accordion Module Item by Linking

|

The Divi accordion module starts with the first accordion item open by default. If you'd like to be able to control which accordion item is opened when linking to the page, you can do so with the following jQuery code:

<script>
	jQuery(function($) {
		
		setTimeout(function(){
			
			var query = window.location.search.substring(1);
			var params = query.split('&');
			
			var accordion_id = '';
			var toggle_id = '';

			for (var i = 0; i < params.length; i++) {

				var param = params[i].split('=');
				
				if (param[0] !== undefined && param[1] !== undefined) {
					param[1] = decodeURIComponent(param[1]);
					
					if (param[0] === 'ao' && /^[-_a-zA-Z0-9]+$/.test(param[1])) {
						accordion_id = param[1];
					}
					
					if (param[0] === 'ai' && /^\d+$/.test(param[1])) {
						toggle_id = param[1];
					}
				}
			}
			
			if (accordion_id !== '' && toggle_id !== '') {
				$('#'+accordion_id+'.et_pb_accordion .et_pb_toggle:nth-of-type('+toggle_id+') .et_pb_toggle_title').trigger('click');
			}
	
		}, 100);
	});
</script>

With this code in place, you can now change the link to a page such as https://www.mysite.com/mypage/ to https://www.mysite.com/mypage/?ao=myaccordion&ai=3 to open the third item of the accordion module with id "myaccordion". 

You may also like to combine this with my tip on making accordions start closed to minimize the visual effect of the first accordion item being closed on page load.

Scroll to the Accordion's Location

If you'd like to also have the page scroll to the location of the accordion, you can do so by adding the accordion module's id as a hash to the URL, giving:

https://www.mysite.com/mypage/?ao=myaccordion&ai=3#myaccordion

If you want to include the link in this form on the same page as the target accordion (e.g.in a button module), note that Divi may intercept clicks on the link and try to scroll directly to the accordion without opening the accordion item.

To solve this, first add "disable_click_handlers" as a class to the button or link. In the case of the button module, you can add the class at:

Button Settings > Advanced > CSS ID & Classes > CSS Class

Then add the following jQuery to your site: 

<script>
jQuery(function($){
	$('.disable-click-handlers').unbind('click');
});
</script>

You can add the jQuery at:

Divi > Theme Options > Integration > Add code to the head of your blog

Now the link should work correctly even if it is on the same page as the accordion.

This post may contain referral links which may earn a commission for this site

Divi Booster

Hundreds of new features for Divi
in one easy-to-use plugin

33 Comments

    • Hey cindi, I think what's happening on your site is actually a general Divi issue and not related to the accordion linking. Basically it looks like the browser's own handling of the scroll happens first, before Divi's own scroll handling loads. Then Divi's scroll handling takes effect, but the first thing Divi does is scroll to the top of the page before scrolling down. So you get the effect of scrolling to the accordion, back to the top and then back to the accordion again. I've come up with a way to disable Divi's scroll back to the top which I think should sort the issue for you. I've just published a post on it:

      Fix Divi Anchor Links Jump Back to Top

      I hope it helps, but let me know if you continue to have the issue after that.

      Thanks!
      Dan

      Reply
  1. Thank you so much for your work here! It's working great – except I get a strange transition where it shows the accordion opening, jumps to the top of the page, then scrolls back down to the correct spot. If I refresh the page (with the accordion link in the URL) it works fine. Any ideas why its jumping to the top of the page?

    https://www.taxrightaccountants.com.au/services/?ao=myaccordion&ai=4#myaccordion

    Thank you!

    Reply
    • Hey Tim, I don't think the issue is directly related to the code in this post – I see that the same issue (an initial scroll down and then scroll back to the top) happens on the first load of any page with a hash component in the URL (corresponding to an ID of some element on the page).

      I notice in your child theme you have the following code:

      jQuery(function ($) {
          $( document ).ready(function() {
              // accordion
              if (typeof openers.accordion !== 'undefined') {
                  var accordion_element = '#my-accordian .' + openers.accordion + ' h5.et_pb_toggle_title';
                  $(accordion_element).click();
                  $("html, body").animate({ scrollTop: $('#my-accordian').offset().top }, 1000);
              }
              // tab
              if (typeof openers.tab !== 'undefined') {
                  var tab_element = '#my-tabs .' + openers.tab + ' a';
                  $(tab_element).click();
                  $("html, body").animate({ scrollTop: $('#my-tabs').offset().top }, 1000);
              }
          });
      });
      

      It seems to be be trying to do something similar to the code in the post – i.e. click on an accordion and scroll to it. I'm not 100% sure if it's what's causing the issue, but I think there's a chance that it is. If it isn't currently in use (I couldn't find a #my-accordian element in the pages I checked) then I'd suggest removing it from the child theme functions.js file to see if that solves the issue.

      If not let me know and I'll keep digging…

      Thanks!

      Reply
      • Hey Tim, I don't know if you're still having trouble with this or not, but I think I may have tracked down the cause and come up with a solution:

        Fix Divi Anchor Links Jump Back to Top

        Hope it helps!

        Reply
    • Hey Bryan,

      It looks like you're currently trying to use the alternative method from this BeSuperfly post, right? They seem to be having some formatting issues on that post at the moment, which are causing the straight single quotes in the code to display as curly single quotes instead. The code on your site seems to have picked up these curly quotes and as such isn't valid code / isn't running correctly.

      I've sent a message to BeSuperfly and hopefully they'll be able to correct the post soon. In the meantime, here's a copy of the code from your page, with the curly quotes changed to straight. If you replace the code on your page with this, that will hopefully getting it working. Note that I haven't tested it myself, but give me a shout if you still have issues after that and I'll take a deeper look:

      (function($){
      let hash = '';
      function doClasses(url){
      hash = url;
      let target = '.' + hash,
      module_check = hash.split("_");
      if(module_check[2] == 'accordion' || module_check[2] == 'toggle'){
      if(!$(target).hasClass('et_pb_toggle_open')){
      $(target).toggleClass('et_pb_toggle_open et_pb_toggle_close');
      $(target).siblings('.et_pb_accordion_item').removeClass('et_pb_toggle_open').addClass('et_pb_toggle_close');
      }
      }
      if((module_check[1] == 'advanced' && module_check[2] == 'tab')){
      $(target).click();
      }
      }
      function scrollToElement(el){
      let elementTop = $('.' + el).offset().top,
      headerTop = 90;
      if($('body').hasClass('et_fixed_nav')){
      headerTop = $('header').height() + 90;
      }
      let scrollTo = elementTop – headerTop;
      $('html, body').animate({scrollTop: scrollTo + "px"}, 300);
      }
      function loadToggle(){
      if( window.location.hash.slice(1) && (window.location.hash.slice(1).includes('accordion') || window.location.hash.slice(1).includes('toggle') )){
      doClasses(window.location.hash.slice(1));
      scrollToElement(window.location.hash.slice(1));
      }
      }
      function clickToggle(){
      $('a.et_pb_button').click(function(e){
      const href = $(this).attr('href'),
      splitHref = href.split('#'),
      postHref = splitHref[1];
      doClasses(postHref);
      scrollToElement(postHref)
      });
      }
      $(document).ready(function(){
      loadToggle();
      $('a.et_pb_button').off();
      clickToggle();
      });
      })(jQuery)
      

      I hope that helps!
      Dan

      Reply
  2. Hi! Thank you for this very helpful post! This is exactly what I was looking for, but it doesn't work for me…
    I did try first with my original full page module which has 2 links (Schedule v1 and V2). I used both to try the 2 alternatives, with no luck. Because it was not really using the Button modules, I just added a line with 2 buttons (Version 1 and Version 2), but again no luck…

    The URL of the test page is: https://ParoisseBrossard.org/z-accueil

    Do you have an idea of why it doesn't work ?

    Thanks
    Gaston

    Reply
    • Hey Gaston! Your accordion id includes a hyphen ("ma-paroisse"), but my code was only allowing ids consisting solely of letters / numbers. Since a hyphen is perfectly valid in a CSS ID, I've updated the code in the post above to allow them. If you replace the code you're currently using with the latest version of the code in the post, I think that should get it working. Let me know if it still doesn't work after that. Thanks!

      Reply
  3. I've been trying to find a similar solution for the Toggle Module of Divi. Is there any way to get a Toggle Module to open when linking to it from another page? Thanks!

    Reply
      • Perfect! Thanks! I was trying to modify the code on my own, but to no avail!

        Reply
        • You’re welcome, Matthew!

          Reply
  4. Hi Dan,

    Using Divi Booster with success, great addition to Divi!

    Have accordion windows closed now while loading page, but I don't
    succeed in scrolling to and opening one specific toggle with a textlink. Tried a lot scripts, nothing works. Help!

    Is Divi Booster maybe overruling the scripts I tried?

    Reply
    • Hey Farald, I took a look at the page linked in your comment, and can see the closed accordion. But it doesn't look like it has either the code from the page above added, or an ID set on the accordion (as required by the post). Is there any chance you're able to set up an example with those added, so that I can look into what might be the issue for you? If you have already added them, try clearing your caches in case the changes just haven't been applied to the live page yet. I don't think Divi Booster should affect the script in this post, but I can't say for certain that it would work alongside scripts from elsewhere (if you have an example using scripts from another source, perhaps you can send over a link to those pages too so that I can check it out?). Cheers!

      Reply
  5. Hello, I am also having trouble with the code successfully scrolling down the page, but not opening the accordion item.

    I have used the script to have accordion items closed by default.
    I am using a menu link to scroll down the page and (hopefully – if it will work) open the accordion item.

    My site is https://madocwfmchurch.ca.
    Then click the "give" link in the menu at top right.

    Thank-you

    Reply
    • Hi Brandon, I can see two issues here.

      1) The first is an easy one – the URL currently in the Give link is:

      https://madocwfmchurch.ca/?ao=myaccordion&ai=3#give

      The "ai" value gives the index of the toggle with in the accordion. In the case of your "myaccordion", the "Giving Options" toggle is the first toggle, so the link should be:

      https://madocwfmchurch.ca/?ao=myaccordion&ai=1#give

      (There is no third toggle in "myaccordion", which is why the ai=3 form of the link wasn't opening anything)

      2) The modified link will work when entered directly in the address bar or linked to from another page. But you may notice that it still doesn't work when the "Give" link is clicked while on the homepage. The problem here is that Divi is intercepting the link to do a smooth on-page scroll to the element given in the hash (i.e. "#give"). In the process it is ignoring the ao / ai parameters entirely. It's possible to disable Divi's intercepting of the link entirely, which will get everything working, but leads to a bit of a clumsy page refresh. For a nicer effect you could add the following jQuery to your site (e.g. in "Divi > Theme Options > Integration > Add this to the head of your blog"):

      <script>
      jQuery(
      	function() {
      		jQuery('body.home #et-secondary-nav .menu-item:nth-child(2) a').click(
      			function() {
      				jQuery('#myaccordion .et_pb_toggle:nth-child(1) .et_pb_toggle_title').click();
      			}
      		);
      	}
      );
      </script>
      

      It basically says if the second link in the secondary nav bar (i.e. the "Give" link) is clicked while on the homepage, simulate a click on the first item in the "myaccordion" accordion. This, combined with Divi's own handling of the scroll, should give you a smooth effect of scrolling to the "Giving Options" which is opened in the process.

      PS. As a side note, the code above is slightly brittle and would need to be updated if you, for example, change the order of the menu items / toggles. I could likely be improved by assigning classes / ids to the elements in question so that the code will automatically handle such changes. If that's something you think you'll need, let me know.

      Hope that helps!

      Reply
  6. I have accordions within accordions in my site (made possible by inserting shortcode to the parent accordion). Is it possible to make a link that opens a parent accordion, then the child one within the parent accordion and scroll to the right place?

    Inception lol

    Reply
    • Hey Tatu, I haven't had a chance to try it yet, but the code above ultimately just simulates a click on the accordion title, so I think you should be able to open the child by:

      1) Adding a second copy of the code
      2) Changing the parameter names (i.e. where you see "param[0] === 'ao'" and "param[0] === 'ai'" in the code) to, say "co" and "ci",
      3) Using these parameter names in the URL, alongside the old – something like: https://www.mysite.com/mypage/?ao=myaccordion&ai=3&co=childaccordion&ci=1
      4) Increasing the timeout in the third last line (i.e. this bit "}, 100);". The 100 is in milliseconds, but you'll need to wait for the parent to do its opening animation – maybe set to 1000 (i.e. 1 second) and adjust up or down as needed.

      For scrolling to the correct place, using the module id as the hash will probably only work on the parent accordion. If that won't cut it, let me know. Thanks!

      Reply
  7. Hello! Thank you for this helpful post! I am trying to set up a page in Divi with accordions, and I have successfully gotten the accordions to stay closed by hiding the first one with css code. I've also created a separate accordion module for each "pop-down" so that I can give them all separate ids. However, I'm having the same problem as Han – the JQuery to open the accordions only scrolls down the page, it doesn't open the accordions. I am not using a button, however. I set up a sidebar menu that has anchor links to each accordion. Any help would be much appreciated!

    Here's the link to the page I am creating: https://staging3.biblicalmissiology.org/?page_id=4492

    Reply
    • Hi Julianna, you should be able to use a similar technique to the one I suggested to Han. However, you need to modify it to remove the click handler from your sidebar links instead of the button. Try this:

      <script>
      jQuery(function($) {
      	setTimeout(function(){
      		$('#menu-articles a').unbind('click');
      	}, 100);
      });
      </script>
      

      Let me know if it doesn't help. Thanks!

      Reply
  8. Hi, great code, but my anchor link (text no button) also does not work when I link from the same page. It works properly if I link from another page.
    I guess my problem is more or less the same as Han's is. However, I would like to use a text link, not a button. Can you help me?

    Reply
    • Hi Martijn, did you get it working? I just tested out the links you have in your footer and they seem to be working correctly for me. Perhaps I'm missing something though? If so, perhaps you can give me talk me through the steps to reproduce the issue and also let me know what browser you're using? Thanks!

      Reply
  9. Where does the script go? Divi Options-Head? I can't get this to work. :(

    Reply
    • Hi Marna, it should work there, yes… any chance you’re able to send me an example of one of your links so that I can try to figure out what’s going wrong? Thanks!

      Reply
  10. Hi, found this snippet, thanks you for your useful code!
    It works very nice from other pages, but when I use the link from the same page, the accordeon does not open.
    Is there a solution maybe?
    Thanks in advance!

    Reply
    • Hi Han,

      I'm assuming you're using the link within a button module? Divi runs a bit of JavaScript code that intercepts button clicks and tries to scroll to the place on the page without the page being reloaded. However, this code ignores any parameters added to the page URL (such as by the above method) and overrides the URL. One option is to give your button an ID such as "mybutton" and add the following code alongside that given in the post:

      <script>
      jQuery(function($) {
      	setTimeout(function(){
      		$('#mybutton').unbind('click');
      	}, 100);
      });
      </script>
      

      This will deregister Divi's code for handling the click, and allow the link to work as intended. I hope it helps!

      Reply

Submit a Comment

Comments are manually moderated and approved at the time they are answered. A preview is shown while pending but may disappear if your are cookies cleared - don't worry though, the comment is still in the queue.

Your email address will not be published. Required fields are marked *.