This question kept coming up on the Tabs widget for page builder plugin support, so I decided to write this short post about it.
How can we link to a specific tab?
This can be done with a bit of custom JavaScript code.
First we have to add a class and a href to the link/button, that will trigger the tab to open. For this example we will use this link <a class="js-trigger-tab" href="#tab-test-2">open test tab</a>
. In the href you have to write the ID of the tab content div (in our example: #tab-test-2) that you want to open and you also have to set the class of the link to js-trigger-tab.
Then we need to add the JS code, which will open the tab:
1 2 3 4 5 6 7 8 |
<script> (function($) { $(document).on( 'click', '.js-trigger-tab', function( event ) { event.preventDefault(); $( 'a.nav-link[href="' + event.currentTarget.hash + '"]' ).click(); }); })(jQuery); </script> |
That’s it 🙂
Let me know, if you have any questions in the comments section below.
Thank you for this post, the code works fine within tabs on the same page. However, I didn’t manage to get this work if the target tab is on the other page. Is it possible to make a link to a tab on another page, and how the href parameter should be formatted in that case?
Hi Tomi,
the answer to your question is on this page: https://wordpress.org/support/topic/tabs-in-another-page/
Take care!
Thanks! WP-Tab-Anchors solved the issue perfectly.
Great! 🙂
Hi Gregror! Love the plugin
What would you add to the code, if I what the page to scroll to the tab on a click
The onpage tab-links are somewhat higher that the acctual tabs. So I need the page tot scroll down when a tab-link is clicked.
Can you add this?
Hi Ruben,
you can add the “animate” on the body, to scroll to the element. More info here: https://stackoverflow.com/questions/6677035/jquery-scroll-to-element
Have a nice day!