Using anchor links to open accordions and tabs in Divi – from another page!

The most popular article on my blog so far (by way of comments on it) is the one on Using anchor links to open accordions and tabs in Divi. It’s so popular that when the demo page broke recently I even had a few people comment to ask if the process still worked with newer versions of Divi (it does, by the way).

It being the most popular article, the most popular question I get about it is “How do I link to and open an accordion or tab, from an external page?” Well, today I share that solution.

Before we begin – This article is going to be a little more advanced than my usual Divi posts. This is because it is going to require delving into the world of PHP and WordPress action hooks. For the purposes of this article I am not going to delve too deeply into those topics, so I do suggest reading the relevant documentation on WordPress.org. Also, for the purposes of this article, you are going to need to know how to include PHP into your WordPress site (either via a Divi child theme or a plugin). If you are new to PHP I recommend reading my Child Theme series, especially the article on Making child themes part of your development best practice. For this article, we’ll use a child theme, because it’s the easiest way.

Ok, all caught up? Good, let’s begin!

Preparation: Understand Query Strings

The first thing you need to understand is query strings. Query strings are not something you see a lot of lately (as pretty permalinks are the norm) but they are what existed before permalinks were made popular. Query strings look something like this:

 http://mycooldomain.com/?post_name=my-cool-article 

See how I am specifying that post_name is equal to my-cool-article after the question mark sign? This is a query string. In this string I am passing the variable post_name and giving it a value of my-cool-article. Once the url before the query string loads (in this case just the home page of the domain) I can check for that variable using the global PHP $_GET variable array and, if it exists, do something with it.

$passed_post_name = $_GET['post_name'];
// do something with the $passed_post_name variable

In order to open a specific tab or accordion on page A from page B, I need to setup my anchor links on page B to point to page A, but those links should also include a query string variable, in this instance the name of the accordion or tab item I want to open.

So, for the purposes of this topic my query string will something look like this

 ?et_open_accordion=et_pb_accordion_item_1 

or

 ?et_open_tab=et_pb_tab_1 

You’ll see that I am passing the class identifier of the accordion or tab item to open as the value. (more on this later)

Step 1: Making some jQuery changes

Let’s first take a look at the accordion ‘open’ snippet I posted in the original article:

jQuery(function ($) {
//accordion
$('#open-accordion-dance a').on('click', function(event){
$('#my-accordian .et_pb_accordion_item_1 .et_pb_toggle_title').click();
$("html, body").animate({ scrollTop: $('#my-accordian').offset().top }, 1000);
});
//tab
$('#open-tab-dance a').on('click', function(event){
$('#my-tabs .et_pb_tab_1 a').click();
$("html, body").animate({ scrollTop: $('#my-tabs').offset().top }, 1000);
});
});

The important thing to look at is the css class identifier for the accordion or item we’re triggering the click on, in this case .et_pb_accordion_item_1 or .et_pb_tab_1. See how this is the same as the value being passed in the query string above. What we need to do now is to be able to specify that value as a JavaScript variable somehow and pass that variable into the JavaScript, to trigger the click of our selected accordion item, when the page loads.

The second thing we will need to do is make sure that this code only fires, once the entire document has loaded. Currently it waits for you to click a link on the same page, but now we’ll be loading the page with the accordion or tab content and then triggering the click.

The change to the JavaScript looks like this:

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);
}
});
});

Note how I have changed the et_pb_accordion_item_1 and et_pb_tab_1 to openers.accordion and openers.tab and instead of those variables being inside the class selector string they are being concatenated to the string (see, I told you this was a little more advanced). I’m also wrapping the entire thing inside a $( document ).ready(function() {} and removing the on(“click”) event handlers and checking if there is an instance of either openers.accordion or openers.tab. If either exists it will fire the relevant ‘open and animate to’ code.

 

Step 2: Mix in some PHP

Right, so now that we have this updated JavaScript we need to setup those openers variables, based on the query string. Do to this we need to do two things a) enqueue the JavaScript in the child theme and b) pass some PHP variables to the JavaScript. To achieve this we’ll put all our PHP code into a functions.php file of a child theme.

Instead of using the Divi Theme Options Code Integration tab for the JavaScript, we need to save it in a file in our child theme and hook a function into the wp_enqueue_scripts action hook (the same one used to enqueue child theme CSS). It looks something like this:

function my_theme_enqueue_scripts() {
wp_register_script( 'some_handle', 'path/to/myscript.js' );
wp_enqueue_script( 'some_handle' );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );

We also need to make the PHP variable available to the script. This is done by using the wp_localize_script function, which allows you to pass any variable from PHP to the JavaScript script you are enqueuing using wp_localize_script.

function my_theme_enqueue_scripts() {
wp_register_script( 'some_handle', 'path/to/myscript.js' );
$variable_array = array(
'my_javascript_variable' => 'some value'
);
wp_localize_script( 'some_handle', 'javscript_object_name', $translation_array );
wp_enqueue_script( 'some_handle' );
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_scripts' );

What this does is pass a PHP array of variables ( $variable_array  ) into the JavaScript layer as a JavaScript object ( javscript_object_name ) and makes them available to use in the JavaScript layer.

Finally we’ll need to capture the variables passed from the query string. That looks something like this:

$variable_array = array();
if( isset( $_GET['et_open_accordion'] ) ){
$variable_array['accordion'] = $_GET['et_open_accordion'];
}
if( isset( $_GET['et_open_tab'] ) ){
$variable_array['tab'] = $_GET['et_open_tab'];
}

There are also some other things we need to setup, like defining path urls for enqueing files and setting up the Divi parent stylesheets. Again I’m not going to go into too much detail, but the final functions.php file looks like this:

define( 'PARENT_THEME_URL', trailingslashit( get_template_directory_uri( ) ) );
define( 'CHILD_THEME_URL', trailingslashit( get_stylesheet_directory_uri( ) ) );

function divi_child_theme_enqueue_styles() {

$parent_style = 'divi-style'; // This is the 'parent-style'.

wp_enqueue_style( $parent_style, PARENT_THEME_URL . 'style.css' );
wp_enqueue_style( 'divi-child-style', CHILD_THEME_URL . 'style.css', array( $parent_style ) );

$functions_script = 'divi-child-functions';

$data = array();

if( isset( $_GET['et_open_accordion'] ) ){
$data['accordion'] = $_GET['et_open_accordion'];
}

if( isset( $_GET['et_open_tab'] ) ){
$data['tab'] = $_GET['et_open_tab'];
}

wp_register_script( $functions_script, CHILD_THEME_URL . 'functions.js', array( 'jquery' ), '1.0', true );
wp_localize_script( $functions_script, 'openers', $data );
wp_enqueue_script( $functions_script );

}
add_action( 'wp_enqueue_scripts', 'divi_child_theme_enqueue_styles' );

Step 4: Putting it all together.

So, you have your functions.php file, retrieving the passed variables, setting up the javascript variables and enqueing the relevant javascript file to make it all work. All you have to do now is create a page with anchors that link to the correct location, including your query strings. And we’re all set.

To make it easier for you to test out, I’ve create a very basic Divi child theme, including all the above code, that you can just install, configure and use out of the box. You can grab this child theme demo from the GitHub page.

One thing to note, this article and child theme are for the purposes of explaining the basics of linking to open tabs or accordions. In the real world you should be considering escaping the query variables in the PHP to ensure no one injects any dodgy code into your site. This article is a good place to start.

Happy Divi-ing.

Update: Thanks to Nathan Duvall for pointing out how to manage this with Divi toggles.

(function($){
$(window).load(function(){
var et_hash = window.location.hash;
if(window.location.hash) {
$( '.et_pb_toggle' + et_hash ).removeClass('et_pb_toggle_close').addClass('et_pb_toggle_open');
}
});
})(jQuery)

Credit: https://bernadot.com/divi-theme-how-to-open-toggled-modules-with-a-url-hashtag/


Posted

in

by

Tags:

Comments

83 responses to “Using anchor links to open accordions and tabs in Divi – from another page!”

  1. Jon Avatar
    Jon

    Thoughts on making this into a plugin? So that non-developers could just add the appropriate tab URL to their href, and have it “just work”?

  2. Terry Hale Avatar
    Terry Hale

    Another great article, Jonathan! Thanks for the reminder about wp_localize_script(). It’s a very powerful but underutilized development tool for sure.

    1. Jonathan Avatar
      Jonathan

      Thanks Terry, glad you found it useful.

      In my old non WP days we used to have to inject the JavaScript variable by echoing out the php variable (something like this)

      var js_var = [php echo $php_var ]

      Very nasty 😉

  3. Renee' Avatar
    Renee’

    Hi Jonathan – Will this work for say click anchor link from one module and have it open a different module on the same page, not different page?

    1. Jonathan Avatar
      Jonathan

      Hi Renee, I think what you need is my “Using anchor links to open accordions and tabs in Divi” article, which I’ve linked at the top of the article. Here’s the url for convenience.

      https://jonathanbossenger.mystagingwebsite.com/using-anchor-links-to-open-accordions-and-tabs-in-divi/

  4. Nathan Duvall Avatar

    Great article, Jonathan! I was actually looking for something similar, but for toggles. Apparently the process is a little easier with those vs. accordions/tabs. For anyone else needing this functionality for tabs, it’s just a matter of giving each toggle a unique ID, copy/pasting this code into the integration tab and then setting up the link.

    (function($){
    $(window).load(function(){
    var et_hash = window.location.hash;
    if(window.location.hash) {
    $( ‘.et_pb_toggle’ + et_hash )
    .removeClass(‘et_pb_toggle_close’)
    .addClass(‘et_pb_toggle_open’)
    }
    });
    })(jQuery)

    Credit: https://bernadot.com/divi-theme-how-to-open-toggled-modules-with-a-url-hashtag/

    1. Jonathan Avatar
      Jonathan

      Thanks Nathan, glad you found the article useful. You may or may not remember this, but it was you who first introduced me to the Facebook Divi Communities 😉

    2. Norman Visser Avatar
      Norman Visser

      Hi Nathan & Jonathan and thanks a million for this.Any chance of getting this to work with Divi 3.22+ ? I notice that it no longer opens the toggle (we’re trying this specifically for toggles) Ie. we’ve set it all up and the anchor links work, but the toggle does not open up anymore.

      Any advice in the right direction would be deeply appreciated.
      Thanks again for this.

      1. Lukas Avatar
        Lukas

        Hi Nathan & Jonathan and all.
        Same question here: Any chance of getting both (accordion or toggle) to work with Divi 3.22+ ? What has changed?

    3. detelinka Avatar
      detelinka

      Thans a lot!
      I change a little to close all other toggles, and open link with new hash according toggle id

      var et_hash = window.location.hash;
      if(window.location.hash) {
      $( '.et_pb_toggle' + et_hash )
      .removeClass('et_pb_toggle_close')
      .addClass('et_pb_toggle_open');
      $("html, body").animate({ scrollTop: $( '.et_pb_toggle' + et_hash ).offset().top }, 1000);
      }

      // open Toggle module if URL that was clicked on the same page has the same hash
      $(“.et_pb_toggle_item”).click(function(){
      var et_hash = this.hash;
      // close other toggles before opening the new one
      $(‘.et_pb_toggle’)
      .removeClass(‘et_pb_toggle_open’)
      .addClass(‘et_pb_toggle_close’);
      $(‘.et_pb_toggle_content’).hide();
      // open the toggle that has the hash
      $( ‘.et_pb_toggle’ + et_hash )
      .removeClass(‘et_pb_toggle_close’)
      .addClass(‘et_pb_toggle_open’);
      $(‘.et_pb_toggle’ + et_hash +’ .et_pb_toggle_content’).show();
      window.location.href = ‘#’+$(this).attr(‘id’);
      $(“html, body”).animate({ scrollTop: $(this).offset().top }, 1000);
      });

  5. Izzy Wyer Avatar

    Hi there

    Great article although I am worried I may have missed something as it isn’t quite working how I expected, both links I have put in just go to the same open tab.(I am not very familiar with scripting so if you could point me in the right direction that would be great).

    I basically have 2 top level main menu items which when clicked I would like to open up not only the relevant page but also open the correct highlighted tab.

    I have implemented from the above tutorial, i.e.:

    1) Added the code to a functions file in the child theme:

    <?php

    add_action( 'wp_enqueue_scripts', 'my_enqueue_assets' );

    function my_enqueue_assets() {

    wp_enqueue_style( 'parent-style', get_template_directory_uri().'/style.css' );

    }

    define( 'PARENT_THEME_URL', trailingslashit( get_template_directory_uri( ) ) );
    define( 'CHILD_THEME_URL', trailingslashit( get_stylesheet_directory_uri( ) ) );

    function divi_child_theme_enqueue_styles() {

    $parent_style = 'divi-style'; // This is the 'parent-style'.

    wp_enqueue_style( $parent_style, PARENT_THEME_URL . 'style.css' );
    wp_enqueue_style( 'divi-child-style', CHILD_THEME_URL . 'style.css', array( $parent_style ) );

    $functions_script = 'divi-child-functions';

    $data = array();

    if( isset( $_GET['et_open_accordion'] ) ){
    $data['accordion'] = $_GET['et_open_accordion'];
    }

    if( isset( $_GET['et_open_tab'] ) ){
    $data['tab'] = $_GET['et_open_tab'];
    }

    wp_register_script( $functions_script, CHILD_THEME_URL . 'functions.js', array( 'jquery' ), '1.0', true );
    wp_localize_script( $functions_script, 'openers', $data );
    wp_enqueue_script( $functions_script );

    }
    add_action( 'wp_enqueue_scripts', 'divi_child_theme_enqueue_styles' );

    2) Given the tabs module the name my-tabs in the custom css field

    3) Added custom links to my main navigation, (nb I am working locally) i.e.:
    a) Sunday Worship points to: http://stjames.dev/community-outreach/#my-tabs|0
    b) Sunday School points to: http://stjames.dev/community-outreach/#my-tabs|4

    However at the moment when I click on the menu items they go to the right page (community-outreach) which is great, however they both only show the first tab opened (Sunday Worship), darn!

    My Questions:

    1) How do I get the second link to open the correct tab, please? I think I missed something somewhere 🙂
    2) Also will the links also work ok when they are accessed from the page with the tabs too?

    Thanks so much

    1. Jonathan Avatar
      Jonathan

      Hi Izzy

      You need to setup the links in the main navigation correctly. Instead of

      http://stjames.dev/community-outreach/#my-tabs

      you will need to do something like

      http://stjames.dev/community-outreach/?et_open_tab=et_pb_tab_1

      where et_pb_tab_1 is the class of the tab you want opened. In the case of accordions and tabs the numbering starts at 0, so et_pb_tab_1 is the second tab.

      1. Izzy Wyer Avatar

        Hi Jonathan, thanks for getting back to me so quickly and pointing that out for me – I have now got it working correctly.

        One more quick question when it goes to the correct tab the page scrolls down a little bit thus obscuring the highlighted tab name – it looks like the page scrolls to the top and then hides behind the primary navigation header – is there a way to avoid that at all?

        Thanks so much

        1. Izzy Wyer Avatar

          Hi again – no problem, I think I have worked it out, I removed the:

          $(“html, body”).animate({ scrollTop: $(‘#my-tabs’).offset().top }, 1000);

          bit and the scroll has gone – thanks for the great tutorial 🙂

          Izzy

  6. regina Avatar

    thank you so much for this. this is brilliant! cheers 🙂

    1. Jonathan Avatar
      Jonathan

      My pleasure Regina, I am glad it works for you.

  7. Zac Avatar
    Zac

    When linking to multiple different accordian items, each consecutive one begins to become a little more offset from the top. See my example (open each link in a new tab and compare): http://southeasttax.wpengine.com/linking-page/

    Any solution for this?

    1. Jonathan Avatar
      Jonathan

      Hi Zac

      The code that does the auto scroll is this line

      $(“html, body”).animate({ scrollTop: $(‘#my-accordian’).offset().top }, 1000);

      Basically that is scrolling the window to the top of the accordion. So you could change it to scroll to the top of the opened accordion item by appending the class selector variable for the opened accordion item.

      $(“html, body”).animate({ scrollTop: $(‘#my-accordian .’ + openers.accordion ).offset().top }, 1000);

      Let me know how it goes.

      1. nordie Avatar
        nordie

        what do we have to change to do the same for the “tab version”

  8. Zac Avatar
    Zac

    Nope, looks like it didn’t change anything..

    1. Jonathan Avatar
      Jonathan

      Hi Zac

      If I view the contents of your javascript it looks like you’ve got some funny characters in there instead of double quotes. Possibly because you copy/pasted it from the comments area of this topic.

      http://1vo6uu3gog5h3kvar03edfe0.wpengine.netdna-cdn.com/wp-content/themes/anchor-links-demo-master/functions.js?ver=1.0

      Try fixing that up and it should work

      1. clintdosporra Avatar
        clintdosporra

        Any news on that plugin before I kick this “little” task off

        1. Jonathan Avatar
          Jonathan

          Unfortunately not at this time.

  9. ozzy Avatar
    ozzy

    Hi Jonathan,
    Its working well on my tab case.
    Thanks a lot for share this article and help.

    1. Radu Avatar
      Radu

      Hello Ozzy, how did you manage to make it work? thanks!

  10. Chris Avatar
    Chris

    Great article Jonathan!
    Building in this functionality seems to be to be a fundamental requirement if you have content in Tabs, Accordions and Toggle modules. However, the procedure that you outline is a little outside my capabilities!
    Elegant Themes appear to be neatly sidestepping the issue at the moment, so wouldn’t it be nice if some one could develop a plugin (I would gladly pay for it!), or a complete step by step idiots tutorial?

    1. Jonathan Avatar
      Jonathan

      Hi Chris, thanks for the feedback.

      I am actually in the process of building this into a plugin for general release next week, watch this space 😉

      Regards

      1. Chris Avatar
        Chris

        Fantastic! That’s the best news I have heard in a long time!
        I nominate you for entry into the WP Hall of Fame! 😉

      2. Jon Avatar
        Jon

        Any update on the plugin?

  11. Chris Avatar
    Chris

    Hi Jonathan,
    No pressure!
    Are you any closer to launching the plugin?
    Cheers,
    Chris

  12. Jonathan Avatar
    Jonathan

    At this stage the plugin is still in development, I have to focus on work that pays the bills, but I will wrap it up as soon as I can.

    1. Chris Chapman Avatar
      Chris Chapman

      I’m familiar with that little dilemma!
      If you need a hand with any beta testing, just let me know and I will be happy to help.
      Cheers,
      Chris

  13. TeKno Ziz Avatar

    Ohhh, would love to see this plugin…

  14. Maffix Avatar
    Maffix

    Thanks much Jonathan for this solution, which I really wanted to learn.

    Just one thing is I am little bit slow on getting this.

    How about putting all the jquery scripts, php, and the html, in a zip. I believe by running these files and then studying them by tests will help me on understanding this most looked for solution you have provided.

    Much appreciated for this.

    Thanks,

  15. Edie Etoile Avatar
    Edie Etoile

    Hello,
    Thanks so much for this!

    On the topic of security, since we aren’t printing or writing to a database we apparently need be concerned with the data we are getting from the url (key, value pairs) via the “$_GET[‘et_open_accordion’]” and $_GET[‘et_open_tab’], correct?

    It seems to me that this WordPress function is a close fit:

    https://codex.wordpress.org/Function_Reference/sanitize_title_with_dashes

    as it: “Limits the output to alphanumeric characters, underscore (_) and dash (-). Whitespace becomes a dash.”

    So, if we do:
    sanitize_title_with_dashes( $_GET[‘et_open_tab’] )
    sanitize_title_with_dashes( $_GET[‘et_open_accordion’] )

    it would seem that I’m covering the bases, correct?

    1. Jonathan Avatar
      Jonathan

      Sure, that function would be fine. To be honest, because of how the parameter is only being used to setup some jQuery functionality, I don’t really think you even need to perform any data sanitisation. Just doing something like checking to make sure that the correct string has been passed would be sufficient


      $parameter = $GET['et_open_tab'];
      if ( strpos( $parameter, 'et_pb_tab_' ) !== FALSE ) {
      // setup the javascript object
      }

  16. Edie Etoile Avatar
    Edie Etoile

    Jonathan,
    Thank you.

    I would have been happy if you had just made a plugin; now I’ve learned quite a bit and am understanding what is being done so, I’m ecstatic!

    Love your site and approach!

  17. Dimitri Miller Avatar

    Hi Jonathan,

    Have to deeply thank you for providing such detailed article, it really helped us with our website.

    Perhaps you could explain a bit to me, using your code without a child theme (i know a child theme is recommended, but right now we proceeded without one).

    I’m trying to link a few blurbs from our home page to 6 tabs on our product page. So that every blurb opens it’s respective tab on the product page.

    1. Is it possible to add your javascript code to Divi’s theme options code integration rather then using it as an external file, like described in your article?

    2. What would have to be changed in your PHP code in functions.php if we are not using a child theme? We’re using a snippet plugin to integrate code in our theme’s functions.php

    1. Jonathan Avatar
      Jonathan

      Hi Dimitri

      I’m afraid that I can’t comment on the snippet plugin, I prefer not to use such plugins and implement custom code as either a child theme or a plugin. AS such I don’t know if the wp_localize_script functionality works using that plugin. What I can recommend is if you don’t want to use a child theme, package the code into a plugin.

      As for the JavaScript, there is no reason I am aware of that you couldn’t put it in the Divi’s theme options code integration tab.

  18. Dimitri Miller Avatar

    Hi Jonathan,

    If i were to put the PHP code in to functions.php of the main divi theme directly (without child theme), what would i need to change about it?

    1. Dimitri Miller Avatar

      Figured out, why it wasn’t working for me:

      Your code works perfectly with insertion through a snippet plugin in to functions.php, it was a code for opening toggles, i was running that was conflicting:

      (function($){
      $(window).load(function(){
      var et_hash = window.location.hash;
      if(window.location.hash) {
      $( ‘.et_pb_toggle’ + et_hash )
      .removeClass(‘et_pb_toggle_close’)
      .addClass(‘et_pb_toggle_open’)
      }
      });
      })(jQuery)

      Apparently, i’m not able to open tabs by the css id with that code running (example if css id of the tabs is: my-tabs, then http://site.com/my-tabs|0 and 1 and so on will produce a blank space where the tabs should be on that page).
      If i go to the page url where the tabs are, then they are fine.

      Due to this error in chrome inspect: unrecognized expression: .et_pb_toggle#my-tabs|0

      Another question, if i may: I have pretty long tabs, is it possible to open tab classes (et_pb_tab_0, et_pb_tab_1, etc…) with different auto-scroll to different content on those tabs?

      For instance:

      If i click the anchor linking to et_pb_tab_0 it will open that tab 0 with $(‘#my-tabs’).offset + 150().top }, 1000);

      but if i click the anchor linking to et_pb_tab_1 it will open tab 1 with, say $(‘#my-tabs’).offset + 800().top }, 1000);

      or scroll down to a module/row CSS id?

  19. Alex Avatar
    Alex

    Hello,

    I’ve added ids and classes to sections and im trying to switch them with wordpress menu (divi). I’m trying to do something similar to yours. In browser view works great, when it gets to mobile view it dosnt work anymore.

    Link: http://euro.greekmedia.ro

    I’m trying for about 4days to get this working and i just cant find a solution to fix this up.
    My idea is that it dosnt work because of mobile icon that needs to be pressed before.

    Maybe you have time to look on this.
    Thanks!

  20. Aimee Avatar
    Aimee

    Thanks for the in depth article! It really helped me, with more than just this feature.
    I was looking into creating a child theme for Divi and hit a bug that’s present in WordPress 4.9 that won’t allow editing in the child theme editor. I was starting to wonder if I should bother using a child theme but after seeing the layout of your files clearly in your GitHub sample, I decided to proceed. I wasn’t sure whether .js files should be placed in the same folder as the functions.php, or whether I should still use the areas provided in the Divi theme foe adding extra code.

    Long story short, I understand the file layout now and have working anchors for my tabs! 🙂

    1. Jonathan Avatar
      Jonathan

      That’s awesome to hear, thanks for the feedback Aimee.

  21. Bill Avatar
    Bill

    Jonathan,

    Great articles, liked them both and good code. Question, I am having an issue with the code executing, it goes to the page fine but the accordion flashes by and does not stay open. It only also does only the first link. I checked my URL which was correct.

    1. Jonathan Avatar
      Jonathan

      Bill, do you perhaps have a link where this is happening?

      1. Bill Avatar
        Bill

        http://www.livingandworkingwell.net/home-2/

        Link at bottom says test.

        1. Jonathan Avatar
          Jonathan

          Bill, you have used the JavaScript code as is, without applying the relevant CSS IDs to your accordion. See the previous article where I talk about setting this up.

          https://jonathanbossenger.mystagingwebsite.com/using-anchor-links-to-open-accordions-and-tabs-in-divi/

          1. Adam Avatar

            Jonathan, you were right! I forgot to assign an ID to accordion and tabs.
            Now it works just perfectly.
            Thank you very much!

          2. Bill Avatar
            Bill

            This was perfect, thank you.

  22. Adam Avatar

    Hi, Jonathan. Thank you very much for your great work and article!
    I was going to have a look at your demo, and unfortunately, it doesn’t work for me.
    After I click on http://beta.ukrcanadablog.com/test-page/?et_open_accordion=et_pb_accordion_item_1
    I get this Error in the Console (Google Chrome):

    Uncaught TypeError: Cannot read property ‘top’ of undefined
    at HTMLDocument. (functions.js?ver=1.0:7)
    at i (jquery.js?ver=1.12.4:2)
    at Object.fireWith [as resolveWith] (jquery.js?ver=1.12.4:2)
    at Function.ready (jquery.js?ver=1.12.4:2)
    at HTMLDocument.K (jquery.js?ver=1.12.4:2)

    I would be very happy if you could advise me what am I doing wrong, therefore I could implement your idea to the real website in a future.
    Thank you very much

    1. Jonathan Avatar
      Jonathan

      Adam, it looks like the accordion you want to open doesn’t have an ID of ‘my-accordian’, you need to set the CSS ID value in the Advanced tab of the accordion to match the ID being used in this line

      $(“html, body”).animate({ scrollTop: $(‘#my-accordian’).offset().top }, 1000);

  23. Helen Avatar
    Helen

    Hi, I’m fairly new to css coding and stuff. I have an accordion with treatments on a clients page that I’m making. She wants the treatments in the menu and when people click on the menu-item that it opens up the right part of the accordion. Do I have to put in code for every accordion part? Since in this code it says et_pb_accordion_item_1? Or does that work automatically?

  24. Carrol Avatar
    Carrol

    Thank you for a great article, it is working perfectly.
    I would like to know, is it possible to assign an ID to a specific Accordion item so that I can use that rather than …/?et_open_accordion=et_pb_accordion_item_1
    I have an accordion with over 100 artists, this will be edited over time so it would be easier to link to …/?et_open_accordion=et_pb_accordion_fred_smith rather than have to find and change each and every link when and addition or deletion happens.

  25. Alberto Avatar
    Alberto

    Hi,

    First of all, fantastic solution.
    I’m tried to addapt your explication to my page. The problem is that I’ve got 3 tabs blocks in my page.

    Each tab block has 5 subtabs.

    When I insert your code, only works with the first tab block but I’m not be able to work fine with another 2 blocks.

    It’s possible to find a solution to open any subtabs from an external link?

    Thanks a lot

    1. Jonathan Avatar
      Jonathan

      Hi Alberto, I’m sure it is possible, but it would be something more intricate than the scope of this solution.

  26. Will Avatar
    Will

    You mention on Git Hub to import the Demo.json file but you dont have it included in the archive.

    1. Jonathan Avatar
      Jonathan

      Sorry about that Will, you should be able to get it from the Demo download in this article – https://jonathanbossenger.mystagingwebsite.com/using-anchor-links-to-open-accordions-and-tabs-in-divi/

  27. john paul Avatar

    Hi Jonathan,

    does this still work? I have followed this to the letter with a url of
    https://mydomain.com/town/?et_open_tab=et_pb_tab_1

    But it still opens on the first tab i.e. et_pb_tab_0

  28. Erik Fraser Avatar
    Erik Fraser

    Hi Jonathan,

    Do you think, theoretically speaking, that this concept could be used to target a particular video in a Divi video slider? I’d like to have a page with a slider full of videos, but from other pages, be able to link to, say, mywebsite.com/video/?argument_to_open_third_video, so that upon arrival on the video page, it plays the third video, rather than the first.

    1. Jonathan Avatar
      Jonathan

      Hi Erik, I’ve not used the video slider, but theoretically speaking it probably is possible. One way to do it would be to trigger the slider control that brings the video you want into view, once the page loads. Another way could be to see if you can tell the slider which video should be the first visible one, once the page loads.

  29. Theresa Avatar
    Theresa

    Hi a bit off topic but is there a way to make the Divi tab stay open on page refresh from using a login popup, I am trying to show a download button once logged in but there are many tabs on the page and not keeping the last active open.

    Hope someone has an idea thanks

  30. Aydin Tekay Avatar

    Hi,
    Thanks for this great tutorial. I have tried and manage to go to the particular tab. However, on that tab I have few items for downloading (with a download button), and you script immediately downloads a random file presented in that tab. If the tab does not have any item to download, then the browser stays on the opened tab as your script was intended to do. Long story in short, how can I prevent this automatic downloading?

    with many thanks.

    1. Jonathan Avatar
      Jonathan

      My guess is that this line of code is causing the problem

      $('#my-tabs .et_pb_tab_1 a').click();

      That’s probably targeting all anchor tags inside the first tab, not just the one in the tab list that triggers the tab content to be displayed. If you update it to include the et_pb_tabs_controls class, it should work

      $('#my-tabs .et_pb_tabs_controls .et_pb_tab_1 a').click();

      What this is doing is including the parent un-ordered list HTML element in the CSS selectors, which is the element that contains the list items that contain the tab anchors, so it should make the .click() function call more specific to the tabs, and not also look for anchors in the tab contents.

  31. A Tekay Avatar
    A Tekay

    Jonathan, thank you very much. This did the trick. In addition, the earlier prevented the pagination to function on the very same tab. After adding “.et_pb_tabs_controls “, that problem is also sorted out! Brilliant.

    1. Jonathan Avatar
      Jonathan

      Excellent. Thank you for bringing this to my attention, I have updated the original article.

      1. Jérôme Avatar
        Jérôme

        it’s possible to scroll the window to view the open item in the top of the screen?
        This doesn’t work:
        $(“html, body”).animate({ scrollTop: $(accordion_element).offset().top }, 1000);
        or
        $(“html, body”).animate({ scrollTop: $(‘#accordeon-communes-deleguees .’ + openers.accordion.offset().top }, 1000);
        ??
        Thanks!

        1. Jonathan Avatar
          Jonathan

          Jérôme, you’d have to tell the jQuery animate method what you want to scroll to the top of

          http://api.jquery.com/animate/

  32. René Arbour Avatar
    René Arbour

    Hi Jonathan, There is another thing that I can make working. I am trying to call the anchor from a menu Item. I tried many ways like https://renearbour.ca/experience-travail/#Onglet-experience/“THE JQUERY FUNCTION” that is linked to et_pb_tab_1. Nothing is the right one. There is certainly something I don’t understand. If you can just point me to the good thing to search for, I will do everything possible to find it. Thanks in advance.

  33. infopeterlanephotocom Avatar

    Hi Jonathan,

    following your advise I added this sub navigation under the gallery. It was working fine for a week and then it stopped. I see the code now, it doesn’t start with et_pb_tab_1,2,3,4 … but with et_pb_tab_30. There is no other tabs module on the page. https://peterlanephotography.co.uk/wedding-photographer-london-hertfordshire/
    On another page it starts from et_pb_tab_20….

    I’m very confused, how did it happen?

    Thanks,
    Pete

  34. René Arbour Avatar
    René Arbour

    Hi again Jonathan, I really looked around to understand the detail I miss. Because it becomes more important to me, could you tell me the price of your direct help to make me on the right way to find what I am doing wrong? Thank in advance for your answer.

    1. Jonathan Avatar
      Jonathan

      Hi René, I’m sorry that I’ve not been able to look into this, I’ve been swamped with work.

      If you would like to hire me to help you fix this, please use the Hire Me link in the menu of this blog, that will post a project for me through Codeable and we can communicate from there.

      Regards

      1. René Arbour Avatar
        René Arbour

        Done. Thanks.

  35. Puck Avatar

    Hi Jonathan, thanks so much for this tutorial!
    I’ve got it working (my first with php/JS woohoo), but it does a bit weird when I click on it. https://ph-bouwadvies.pinktest.nl/nieuws-kennis/?et_open_tab=et_pb_tab_4
    It first scrolls down too much, then comes back up again.
    I tried deleting the scrollTop fuction, but it still keeps scrolling there. I realize it’s probably because it’s adding #my-tabs to the url, and Divi sees it as an anchor link. Not sure why that’s happening, I am not that good at analysing php/JS yet.
    It’s ok to scroll there, but that down-up-up thing is annoying.
    Is it possible to have the site just jump to the right place or not jumping at all?

    1. Jonathan Avatar
      Jonathan

      Hi Puck

      It’s hard to say why this is happening, however I notice that when you load the page without any additional URL parameters there is a slight jump once the page loads https://ph-bouwadvies.pinktest.nl/nieuws-kennis/.

      Without digging into the code of the site, I’d guess there is some other animation also being activated.

      You should be able to remove the scrollTop functionality and see the difference, it’s possible that what happened when you removed it the first time was that the JavaScript was cached in your browser, so I’d advise either clearing your browser cache, or using ‘cache busting’ techniques during development.

  36. msbee Avatar
    msbee

    Hey Jonathan! I find this article very helpful. However, what if I want to make the actual tab that when clicked, it will scroll down to its content? Will this code also work? I was hoping to create an anchor text within the tabs title and scroll it down to the content but it doesn’t seem to work.Would you be kind enough to make some suggestions for me? 🙂
    Thank you so much for generously sharing your knowledge with all of us. :))

    1. Jonathan Avatar
      Jonathan

      Hey there, thanks for the comment.

      I’ll be honest I’m not exactly sure what you’re wanting to do. Perhaps if you can share a link to a page and explain what should happen when you click on a specific element?

  37. Stéphane Avatar

    Hi Jonathan,

    great article, I uploaded the child theme to Github, but I can’t find the link for the .json file to import the page.

    Thank you

    1. Jonathan Avatar
      Jonathan

      Hi Stéphane

      The link is available at the bottom of the https://jonathanbossenger.mystagingwebsite.com/using-anchor-links-to-open-accordions-and-tabs-in-divi/ article. I should probably clean things up a little more there…

      1. Stéphane Avatar
        Stéphane

        Hi Jonathan,

        thank you, i will have to clean my eyes more often…

        1. Jonathan Avatar
          Jonathan

          Not a problem. When I checked that page it seems some of the formatting was out of alignment, and the link was partly hidden, so I converted the page to blocks and it seems to have cleared things up.

  38. Michael Avatar
    Michael

    This is excellent! I have no experience using Javascript (only html/css/cms) but I was able to follow your instructions. I’m having difficulty getting the accordion linking to work now, for some reason.

    https://stg54.wpengine.com/services/?et_open_accordion=et_pb_accordion_item_2

    This is the link I’m trying to get to open a mobile accordion item – well this and two other items in the accordion. I’ve got the functions.php and functions.js codes entered in from your child theme and I’ve got the accordion labeled “#my-accordian” but this link seems to not work right now.

    Do you have any idea what might be causing it (remember, I’m 100% new to Javascript here, lol).

    Thanks for being awesome!

    1. Jonathan Avatar
      Jonathan

      Hey Micheal

      Can you point me to the link that you are trying to use to open the accordion item, as well as the accordion you are trying to open, based on that link.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.