Owl carousel and bootstrap tab on a page
This is the best solution:
https://www.youtube.com/watch?v=tKrt9ev4S24
.tab-content > .tab-pane{
display: block;
height: 0;
}
.tab-content > .active{
height: auto;
}
No more JavaScript is needed than the owl carousel option.
Just replace the following lines in the bootstrap.css file and all should work well.
.tab-content > .tab-pane {
visibility: hidden;
height: 0px;
overflow:hidden;
}
.tab-content > .active {
visibility: visible;
height: auto;
overflow: visible;
}
First, I noticed an error in your html. You are missing a closing </div>
tag for your second tab-pane. That's throwing off some of the structure of your markup.
After researching and playing around with this, it seems that this is a known issue. It stems from the fact that Bootstraps tabs are hidden initially. When you try to initialize an OwlCarousel within a hidden element, things go badly because hidden elements have no width, so Owl does not know how much space it has to work with.
My solution is to wait until a tab is shown to initialize the carousel, then destroy the carousel each time the tab is hidden. Here's my JavaScript:
$(document).ready(function () {
initialize_owl($('#owl1'));
let tabs = [
{ target: '#home', owl: '#owl1' },
{ target: '#profile', owl: '#owl2' },
{ target: '#messages', owl: '#owl3' },
{ target: '#settings', owl: '#owl4' },
];
// Setup 'bs.tab' event listeners for each tab
tabs.forEach((tab) => {
$(`a[href="${ tab.target }"]`)
.on('shown.bs.tab', () => initialize_owl($(tab.owl)))
.on('hide.bs.tab', () => destroy_owl($(tab.owl)));
});
});
function initialize_owl(el) {
el.owlCarousel({
loop: true,
margin: 10,
responsiveClass: true,
responsive: {
0: {
items: 1,
nav: true
},
600: {
items: 1,
nav: false
},
1000: {
items: 1,
nav: true,
loop: false
}
}
});
}
function destroy_owl(el) {
el.data('owlCarousel').destroy();
}
And here's a working jsFiddle.