Using Bootstrap 3, I'm dynamically creating some tabs using the way suggested in this post: Add / Remove Tabs Dynamically in Bootstrap - Make created tab active.
It's working great apart from the events firing mechanism.
For instance, when clicking on a statically predefined tab, the shown.bs.tab
event is fired, but this is not the case for any dynamically created tabs.
You can try it on this fiddle adapted from the one proposed in the above post https://jsfiddle.net/HotPheel/v6be62c4/4/
HTML
<div class="container">
<ul class="nav nav-tabs">
<li class="active"><a href="#contact_01" data-toggle="tab">Joe Smith</a><span>x</span></li>
<li><a href="#contact_02" data-toggle="tab">Molly Lewis</a><span>x</span> </li>
<li><a href="#" class="add-contact" data-toggle="tab">+ Add Contact</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="contact_01">Contact Form: Joe Smith</div>
<div class="tab-pane" id="contact_02">Contact Form: Molly Lewis</div>
</div>
JS
$(".nav-tabs").on("click", "a", function(e){
e.preventDefault();
$(this).tab('show');
})
.on("click", "span", function () {
var anchor = $(this).siblings('a');
$(anchor.attr('href')).remove();
$(this).parent().remove();
$(".nav-tabs li").children('a').first().click();
});
$('.add-contact').click(function(e) {
e.preventDefault();
var id = $(".nav-tabs").children().length; //think about it ;)
$(this).closest('li').before('<li><a href="#contact_'+id+'">New Tab</a><span>x</span></li>');
$('.tab-content').append('<div class="tab-pane" id="contact_'+id+'">Contact Form: New Contact '+id+'</div>');});
$('a[data-toggle="tab"]')
.on('shown.bs.tab', function (e) {
var target = $(e.target).attr("href");
alert('clicked on tab' + target);
})
CSS
.container {margin-top: 10px;}
.nav-tabs > li {position:relative;}
.nav-tabs > li > a {display:inline-block;}
.nav-tabs > li > span {
display:none;
cursor:pointer;
position:absolute;
right: 6px;
top: 8px;
color: red;}
.nav-tabs > li:hover > span {display: inline-block;}
Any idea on a method to dynamically create bootstrap tabs preserving the events ?
Thanks a lot for any help.
There's two issues I can identify that if addressed will implement a working solution:
Firstly, your current code doesn't add data-toggle="tab"
to the new <li>
in the logic that adds a new tab/ div. So I updated this to:
$(this).closest('li').before('<li><a href="#contact_'+id+'" data-toggle="tab">New Tab</a><span>x</span></li>');
Secondly, according to other threads e.g. this one, the correct event handling logic would be to hook it like this:
$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
var target = $(e.target).attr("href");
alert('clicked on tab' + target);
})
Update fiddle: https://jsfiddle.net/RobinMackenzie/ym9enL5p/4/
Hope that helps.