Open a Toggle Module when Linking to the Page

|

Divi includes a Toggle module which lets you display a content in an expandable box. The toggle module can be configured to start open or closed. But if you'd like to be able to selectively open the toggle module when linking from another page, here's how to do it.

Open a Toggle Module by Link using jQuery

Setup

First, give your toggle module a CSS ID, such as "mytoggle" at:

Toggle Settings > Advanced > CSS ID & Classes > CSS ID

Option 1: Open the toggle without scrolling to it

If you'd like to open the toggle, but remain at the top of the page (i.e. don't scroll down to the toggle), then add the following jQuery code to your site:

<script>
/* Open a Toggle Module when Linking to the Page */
/* https://divibooster.com/open-a-toggle-module-when-linking-to-the-page/ */
jQuery(function($) {
	setTimeout(function(){
		var query = window.location.search.substring(1);
		var params = query.split('&');
		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] === 'toggle' && /^[a-zA-Z0-9]+$/.test(param[1])) {
					toggle_id = param[1];
				}
			}
		}
		if (toggle_id !== '') {
			$('#'+toggle_id+'.et_pb_toggle .et_pb_toggle_title').trigger('click');
		}
	}, 100);
});
</script>

Now you'll be able to open the toggle when linking to the page containing it, by including a "toggle" parameter in the URL with the ID of your toggle. So, for example, your link to the page might look something like this:

https://divibooster.com/some-page/?toggle=mytoggle

Option 2: Open the toggle and scroll to it

If you'd like to open the toggle and have the page scroll to it, then add the following jQuery code to your site:

<script>
/* Open and scroll to a Toggle Module when Linking to the Page */
/* https://divibooster.com/open-a-toggle-module-when-linking-to-the-page/ */
jQuery(function($) {
	
	// Handle link from another page
	setTimeout(function(){
		var toggle_id = location.hash.substring(1);
		if (toggle_id !== '') {
			$('#'+toggle_id+'.et_pb_toggle .et_pb_toggle_title').trigger('click');
		}
	}, 100);
	
	// Handle same page links
	$('a[href^="#"]').each(
		function() {
			var $link = $(this);
			var href = $(this).attr('href');
			if (href.length > 1) {
				var $toggle = $('.et_pb_toggle'+href);
				if ($toggle.length) {
					$link.unbind('click');
					$(document).on('click', 'a[href="'+href+'"]', function() {
						et_pb_smooth_scroll($toggle, false, 800);
						$toggle.filter('.et_pb_toggle_close').find('.et_pb_toggle_title').click();
					});
				}
			}
		}
	);
	
});
</script>

Now you'll be able to open the toggle when linking to the page containing it, by including the ID of your toggle as the "hash" component of the URL. So, for example, your link to the page might look something like this:

https://divibooster.com/some-page/#mytoggle

If linking to the toggle from within the same page (e.g. in a button module or text link), then only use the ID, rather than the full link, e.g.:

This will cause the browser to smoothly scroll to, and open, the toggle without leaving the page.

Option 3: Open the toggle and scroll to a different element

If you'd like to open the toggle and then have the page scroll to aย different element, e.g. the section containing the toggle, then first follow the instructions for "Option 1" above. Then add the id of the element to scroll to (e.g. an id assigned to the section in "Section Settings > Advanced > CSS ID & Classes") as the "hash" component of the URL, giving a final URL like so:ย 

https://divibooster.com/some-page/?toggle=mytoggle#mysection

Option 3: Open the toggle and scroll to a different element

If you'd like to open the toggle and then have the page scroll to aย different element, e.g. the section containing the toggle, then first follow the instructions for "Option 1" above. Then add the id of the element to scroll to (e.g. an id assigned to the section in "Section Settings > Advanced > CSS ID & Classes") as the "hash" component of the URL, giving a final URL like so:ย 

https://divibooster.com/some-page/?toggle=mytoggle#mysection

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

29 Comments

  1. Hello. Option one is exactly what I am looking for, but I can't get it to work. I can get option two to work perfectly, but the page scrolls further than I want, so I really need option one. Can you check the script just to make sure everything is coded correctly?

    Reply
    • Hi Cindy, I've just run a test with the script from Option One on my own site and it's functioning as expected. Is there any chance you're able to share a link to the page where you're attempting to use this feature? This will let me take a closer look and hopefully pinpoint what's causing the issue. Thanks!

      Reply
      • Thank you. We needed it for an email that is going out this morning, so I just decided to stay with option 2. It isn't ideal, but better than nothing.

        Reply
        • You're welcome, Cindy, and hanks for your update. Should you wish to explore getting option 1 to work down the line, please don't hesitate to reach out. Thanks!

          Reply
    • Hey Richard, sorry to hear you're struggling with it. I took a look but I don't seem to be able to see the code from the post in the page. I'd suggest first trying to clear LightSpeed's cache as it's reporting having cached the page a couple of days ago, so it might be that it's still serving up an old version of the page. If that doesn't help, perhaps try temporarily disabling it entirely just to check. If that doesn't seem to help, are you able to let me know where / how you added the code to the page? Thanks!

      Reply
  2. Forgive me if I missed an answer to this …

    I have a page with four buttons at the top referencing four anchors lower down the page,. The buttons work, but my issue is that whenever I open the page or refresh it, it jumps straight to the first anchor, rather than stay at the top of the page.

    Reply
    • Hey Roderick, are you able to share a link to a page demonstrating the issue? If you're including a hash / anchor in the URL you're using to access the page then when you load / reload the page it would jump to that anchor. Otherwise, there may be some JavaScript somewhere triggering the jump to the first anchor. I should be able to tell you more if I can see the issue in action. Thanks!

      Reply
    • Hi Kalle,

      You don't seem to have a CSS ID (e.g. "mytoggle") set in the toggle module settings. You can set one at:

      Toggle Settings > Advanced > CSS ID & Classes > CSS ID

      Then you will be able to use the ID in the URL like so:

      https://divibooster.com/some-page/#mytoggle

      I hope that helps!

      Reply
  3. Hi Dan
    Gaston again. I decided to change some accordions and create more specific toggle modules. I think I need some clarifications. In the page https://ParoisseBrossard.org/z-accueil I setup 2 toggles at the end of the section Ma Paroisse. ID for one toggle is "intervenants", and ID for the other is "horaire-des-celebrations"

    I added the script, and also added many links to the 2 toggles.

    Let's just take the case of "Horaire des messes".
    There are many variants of it: version 1 is from a full width header module, with a partial URL (without the domain name part), 3 is from a button module, with a partial URL, 4 is from a button module, with a full URL and 5 is from a text module, using a partial URL,

    "Horaire des messes 1" just scrolls to the toggle without opening it, "Horaire des messes 3" scrolls to the toggle without opening it, 4 scrools to the toggle, open it, scroll back to the header, and then scroll to the toggle now opened, 5 does exactly the same as 4.

    I hope that the descriptions are ok, not too confused ๐Ÿค”…

    Could you help me to understand, amongst other things the utilisation of full or partial URL, and if it is possible to not scroll back to the header.

    Thanks again Dan.

    Gaston

    Reply
    • Hey Gaston, I understand what you're saying :)

      I mentioned before to that if you click on a link which is a link to the current page but with a hash component added (e.g. #horaire-des-celebrations), then Divi will intercept the link and scroll directly to the element. This is what is happening with links 1 and 3. Since they are not reloading the page, the code to open the toggle (which is designed to run when the page is first loaded) doesn't run and the toggle doesn't open.

      What is needed is a way to prevent Divi from intercepting the link. I gave you some code for that in the post on opening accordion module toggles by linking, but I see now (and feel like maybe in the recesses of my mind I already knew) that if you provide a full URL instead of a relative URL then Divi won't intercept the link. So if you stick to using the full URL, the page will be reloaded, allowing the toggle opening code to work. If that's not possible / desirable for any reason, then you could use the same "disable-click-handlers" trick I gave in the accordion post.

      The issue with the scrolling back up to the header has me a bit stumped. It only seems to happen when linking from the page, not when accessing the same URL directly. This makes me think it has something to do with the browser trying to restore the state / scroll location of the page prior to the link being clicked, but I haven't quite got my head around it yet. Is there any chance you could try temporarily increasing the timeout on the toggle opening code like so?:

      jQuery(function($) {
      setTimeout(function(){
      var toggle_id = location.hash.substring(1);
      if (toggle_id !== ") {
      $('#'+toggle_id+'.et_pb_toggle .et_pb_toggle_title').trigger('click');
      }
      }, 5000);
      });

      That will delay the toggle opening by 5 seconds and hopefully allow me to see separately what is caused by the reload of the page and what is caused by the toggle opening. Once we figure out the issue, the timeout can be put back to normal.

      As an aside, I originally developed the accordion / toggle opening code to handle the case where the link to the toggle was being placed on some other page. In that scenario the two issues you're encountering don't occur. If you are intending to place the links on other pages (i.e. not the current page with the toggles) then it may make sense to do so now as it may save you some hassle trying to debug the same-page issues.

      On the other hand, if you're actually wanting to (primarily) place the links on the same page as the toggles, there might be a better way to do it. Rather than reloading the page, in theory it should be possible to use Divi's same-page scrolling go directly to the toggle and then automatically open the toggle up when we get there. That should give a smoother experience for the user (and may even save us from the scroll back to header issue). Let me know if you want to go down this route and I'll try to come up with the code to do it.

      Cheers!

      Reply
      • Thank you Dan. It is so kind of you to help me on that matter.

        I will do some testing (and increase the delay), and come back to you.

        Thanks again,

        Gaston

        Reply
        • (By the way, what I like in your solution is that we don't need to specify a special class in the module, which is not possible in a Full width header)…

          Reply
          • Hi Dan

            "If that's not possible / desirable for any reason, then you could use the same "disable-click-handlers" trick I gave in the accordion post." I would like t do it, but sometimes I cannot change the claas of a button (at least when this is one of the 2 buttons within the full width header (or a link within a text). Yes I would primarily place the link on the same page as the toggles.

            I didn't think at first that it would be so much work…

            Thanks Dan

            Gaston

          • Hey Gaston, yeah nothing's ever as easy as it seems at first, hey?!

            I've updated the "Option 2: Open the toggle and scroll to it" section of the post above. The code has been updated to handle links on the same page. If you link to an ID only (e.g. "#some-toggle-id", rather than the full or relative URL), then it will check if the page contains a toggle with that ID. If so, it will scroll to and open the toggle without reloading the page. It should work in the fullwidth header buttons (and elsewhere) and hopefully make things work a bit more smoothly.

            I hope it helps, but give me a shout if you have any questions about it. Cheers!

          • That's fantastic… So smooth, so nice. No need to use a specific css class to do the trick. Therefore it works with all links, not just those triggered by the button module… It's awesome.

            Thanks you so much Dan for your expertise…and your patience!

            Gaston ๐Ÿ˜๐Ÿ‘

          • Youโ€™re very welcome, Gaston. Yeah, itโ€™s definitely an improvement on what we had before. Thanks for all your help / feedback :)

  4. Would it be possible to do all this with just the hash??

    Reply
    • Hey Aaron, absolutely. I've added a section to the post above ("Option 2: Open the toggle and scroll to it") which does it all using the hash. This leads to a neater URL (and shorter code).

      One possible downside to doing it all via the hash is that you can only scroll to the toggle element itself. If you wanted to scroll to, for instance, the section containing the toggle then the original method (now "Option 3") would be needed. An example where you might want to do that is if you had a FAQs section and wanted to open a particular FAQ toggle, but scroll the user to the start of the FAQs.

      Thanks for asking, and I hope that helps!

      Reply
  5. Thanks Dan! This worked perfectly and is just what I was looking for!

    Reply
    • Iโ€™m glad it helped, Matthew! :)

      Reply
      • Dan, follow-up question! Some of my pages have a lot of toggles. Is there any way to get the page to scroll to the toggle I'm linking to and opening from a previous page? Thanks!

        Reply
        • Hey Matthew, I've just added a section to the end of the post explaining how to scroll to the toggle. Hope it helps, but let me know if not. Cheers!

          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 *.