Magento 2 – How to Add Tabs in Custom Module

magento2requirejs

I am creating a custom module. In module created a block view (phtml) and trying to add the custom tabs.
I have tried below:

<div id="tabs">
  <ul>
    <li><a href="#tabs-1">How can I download eBooks?</a></li>
    <li><a href="#tabs-2">What format are Bookstore eBooks?</a></li>
  </ul>
  <div id="tabs-1">
    <p>Once you complete your eBook purchase, the download link for your eBook will be available in your account.</p>
  </div>
  <div id="tabs-2">
    <p>Bookstore eBooks can be downloaded as a PDF, EPUB or MOBI file. They can also be viewed online.</p>
  </div>
</div>
<script>
require(['jquery','jquery/ui'],function($, tabs) {
  $("#tabs").tabs();
});
</script>

Also tried the

require([
    'jquery',
    'mage/tabs'
], function($){

Even added the CSS directly in phtml (testing only).

<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

But they are not working.
Am I missing anything? Please let me guide.

Best Answer

first you need to change your structure to something like this:

<div class="tabs">
    <div class="tab-item" data-mage-init='{"tabs":{"openedState":"active"}}'>
        <div class="tab-title item-title" data-role="collapsible">
            <span data-role="switch"></span>
        </div>
        <div class="tab-content item-content" data-role="content"></div>
    </div>
</div>

this will work with a foreach also, you can set the switch to an <a> element with href that is the tab-item id ( if you want ) to have that anchor go-to-section

UPDATE

require([
     'jquery',
     'jquery/ui'
     ],
     function($, tabs) {
          //Ajax here
     }
);

you should add the tabs init function in the something like this

$(Element_populated_by_Ajax).ajaxComplete(function() {
    $(".tabs").tabs();
});
Related Topic