Twitter Bootstrap - Dynamically Add/Remove Tabs and Tab Content - javascript

Thanks in advance for any and all input/help/advice...
I'm using Twitter Bootstrap tabs to organize some information. The tabs will be located on a form page, and each tab will consist of a "contact form", in which the user can add multiple contacts to this page prior to submitting the whole form.
<div class="container">
<ul class="nav nav-tabs">
<li class="active">Joe Smith<span>x</span></li>
<li>Molly Lewis<span>x</span> </li>
<li>+ Add Contact</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>
</div>
Full code here: http://jsfiddle.net/Harlow/zQnck/34/
I'm trying to mimic the functionality of jQuery UI's "simple manipulation" example of tabs.
(http://jqueryui.com/tabs/#manipulation)
What I currently have will add a new tab, but I want to be able to add a new, unique tab with it's own ID (continuing from the code, like "contact_01, contact_02, etc.") by clicking on the "+ Add New Contact" which will always be the last tab, but not actually have it's own tab content pane. On the other side of dynamically adding content, I want to be able to delete it by click the small "x" on each tab.
--EDIT--
Just to clarify, the jQuery example trigger's a modal upon clicking "New Tab". For my purposes, I just want to create a new tab without inputting the tab name or content (the content will always be the same contact form, and I'm fine with the tab name being the same as the newly generated ID - I will have it automatically update to the contact's name later.)

EDIT: I reproduced the original fiddle as best as I could as both fiddles died.
New fiddle: http://jsfiddle.net/dogoku/KdPdZ/2/
$(".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>New Tab<span>x</span></li>');
$('.tab-content').append('<div class="tab-pane" id="contact_'+id+'">Contact Form: New Contact '+id+'</div>');
});
Note that I removed the hover function and instead used css
.nav-tabs > li:hover > span {
display:block;
}

Dogoku's jsfiddle seems to be 404, so I put together a quick jsfiddle of the solution here: http://jsfiddle.net/xQ3f5/
I updated this to stop the 'active' class being applied to the +Add Contact tab element, as that doesn't correspond to any of the tab elements. I'd also suggest switching the active tab to the newly created one. Here's the javascript:
$(".nav-tabs").on("click", "a", function(e){
e.preventDefault();
if(this.id == "add-contact"){return false;}
$(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 id="contact_tab_'+id+'">New Tab</li>');
$('.tab-content').append('<div class="tab-pane" id="contact_'+id+'">Contact Form: New Contact '+id+'</div>');
$("#contact_tab_"+id+" a").tab('show');
});

Related

jquery tabs access from urls

hello i have jquery tabs and want to access them from url using # but know know how can I full fill with it
requirement is mywebsite.com/#show_page1 will show the page 1 content
and if access from mywebsite.com/#show_page2 will show the page 2 content
here is the my js code
$(window).load(function(){
$(document).ready(function(){
$("#nav_tabbed a").click(function(){
var id = $(this).attr('id');
id = id.split('_');
$("#menu_container div").hide();
$("#menu_container #show_"+id[1]).fadeIn();
// remove classes from all
$("a").removeAttr("style");
// add class to the one we clicked
$(this).css("background-color","#1aaede");
// stop the page from jumping to the top
return false;
});
$("#menu_container #show_page1").show();
});
});
and html i have is
<div id="nav_tabbed">
<a id="show_page1" style="background-color:#1aaede;">Page 1</a> <a id="show_page2">Page 2</a>
</div>
<div id="menu_container">
<div id="show_page1">
<!-- content here -->
</div>
<div id="show_page2">
<!-- content here -->
</div>
</div>
location.hash; will give you the hash value added in the addressbar and you can use it the way you need to. My suggestion is added below.
What seems to me you want to hightlight your link with the hash located in the browser's addressbar and respective div you want to show. If this is what you want to implement then you can try this with slight changes in the markup and js:
CSS:
.active {
color:red;
}
#menu_container div {
display:none;
}
HTML:
<div id="nav_tabbed">
<a href="#show_page1" class='active'>Page 1</a> <!--This lets you add hash in the addressbar-->
Page 2
</div>
<div id="menu_container">
<div id="show_page1" style='display:block;'>Page 1</div>
<div id="show_page2">Page 2</div>
</div>
JS:
$(function () {
// below works for hash added in the browser.
var hash = location.hash;
if(hash.length){
$('#nav_tabbed a').removeClass('active');
$('#menu_container div').hide();
$('#nav_tabbed a[href*="' + hash + '"]').addClass('active');
$('#menu_container div[id*="' + hash.slice(1) + '"]').show();
}
$(document).scrollTop(0);
// below works for click of the anchors
$('#nav_tabbed a').click(function(e){
e.preventDefault();
$(this).addClass('active').siblings('a').removeClass('active');
$('#menu_container div').hide();
$('#menu_container div[id*="'+this.getAttribute('href').slice(1)+'"]').show();
});
});
A sample fiddle.
your posts shows a little confusion on the topic.
so first for explanation:
there are two meanings of a #
in a url, the # is a reference to the location hash.
in jquery, the # is a reference to an element id.
you want to use the hash change in this case.
first of all... why do you wrap the window.load around the dom.ready event?
as far, as i understood, jquery's dom ready fires when the dom is ready, jquerys window.load fires, after all images, iframes, plugins etc. have been loaded. so a dom.ready inside a window.load is kind of unnecessary ...
next: ID's have to be unique - you can't give your anchor the same id as the assigned div!
so let's get down to business - the html:
<div id="nav_tabbed">
Page 1
Page 2
</div>
<div id="menuContainer">
<div id="page1" class="contentTab activeTab">123</div>
<div id="page2" class="contentTab">456</div>
</div>
we use activeLink and activeTab classes to determine which tab is currently open
the css just sets the background of the activeLink:
.activeLink {
background-color:#1aaede;
}
the js:
$(window).load(function(){
$(".contentTab:gt(0)").hide(); //on initial load, we hide all content tabs, despite the first one
$("#nav_tabbed a").click(function () { //the click handler for the navigation only toggles the class to change the background color
$(".activeLink").removeClass("activeLink");
$(this).addClass("activeLink");
})
if(location.hash) //here we check, if there already is a location hash set onload and then change to the desired tab
{
$(".activeTab").hide();
$(location.hash).show().addClass("activeTab");
}
});
//our hashchange event handles the loading of the desired tabs:
window.onhashchange = function () {
if(location.hash!=null) //this checks, wether the hashchange event has been fired, due to a deletion of the hash via url
{
$(".activeTab").hide().removeClass("activeTab"); //hide the current tab
$(location.hash).show().addClass("activeTab"); //show the clicked tab
}else //and per default show the first tab
{
$(".activeTab").hide().removeClass("activeTab"); //hide the current tab
$(".contentTab:first").show().addClass("activeTab"); //show the clicked tab
}
};
http://jsfiddle.net/ex46ndg1/3/

On click, refocus down to tab not functioning. Any suggestions?

On click, refocus down to tab not functioning. Any suggestions? I'm using jQuery of course.
Essentially, I want to refocus down to this tab and open the tab at the same time while refocusing to it.
My code is: here in jsfiddle
JS:
$(document).ready(function(){
//Animates Scrolling
function scrollToAnchor(aid){
var divTag = $("div[name='"+ aid +"']");
$('html,body').animate({scrollTop: divTag.offset().top},'slow');
}
$("#ReadDescription").click(function() {
scrollToAnchor('longdescreadmore');
});
});
HTML, where I'm trying to focus to:
<div class="tab-pane" id="readmore">
<div name="longdescreadmore" id="longdescreadmore">[[DMI:Property name='LongDescription']][[/DMI:Property]]</div>
</div>
HTML, tab header:
<li class="readmore">Read More</li>
HTML, where the click action is taking place:
<h2 id="ReadDescription" class="ReadDescription">Read More</h2>

Creating/setting an active default link when page loads but removing active when others are clicked

As I typed this question I noticed similar question but my approach is different. I did read them but not what I am trying to do, however I did get some ideas.
I have three links (anchor tags) on my page, I am using JQuery to toggle a class between the links based on the link the user clicks. The link becomes active when clicked and I added Cookies to remember the user action.
What I really want to do is set the first link or the link with, example: ID equals one; to be the default. I want the same class (activeLink) which I am using to make the links active to apply to the default. When others are click, the class is than removed and the clicked link becomes active.
That's what I don't know how to do.
My page is a single page.
HTML:
<ul class="yeahBaby">
<li><a id="one" href="#/">Make me default</a></li>
<li><a id="two" href="#/">Example</a></li>
<li><a id="three" href="#/">Example</a></li>
</ul>
JQUERY:
$(document).ready(function() {
var idActive = $.cookie('cookieActive');
if (idActive) {
$('#'+idActive).addClass('activeLink');
}
$('.yeahBaby li a').click(function() {
var id = $(this).attr('id');
$(".yeahBaby li a").removeClass("activeLink");
$(this).addClass("activeLink");
$.cookie('cookieActive', id); //Save anchor id as cookie
$.cookie('cookieActive', id, { expires: 10000});
});
});
CSS:
<style type="text/css">
.activeClass{
color: #999;
}
</style>
Thanks everyone!!
Set the link with id="one" as default in your HTML.
<ul class="yeahBaby">
<li><a id="one" href="#/">Make me default</a></li>
<li><a id="two" href="#/">Example</a></li>
<li><a id="three" href="#/">Example</a></li>
</ul>​​​
Then in jQuery:
// Upon loading the page set default .activeLink
$(window).load(function() {
// If cookie exists
if( $.cookie('active') !== null ) {
// Add .activeLink to last the class in cookie
$.cookie('active').addClass('activeLink');
} else {
// Else set on default
$('#one').addClass('activeLink');
}
});
// Bind click event to each anchor in your list
$('.yeahBaby li a').bind('click', function(e) {
// Remove .activeLink class from current active link
$('.activeLink').removeClass('activeLink');
// Add .activeLink to the link just clicked
$(this).addClass('activeLink');
// Create cookie
$.cookie('active', $(this));
return false;
});​
See it in action here: JSFiddle
-- Update --
See above for addition cookies using the jQuery $.cookie plugin.

collapse and expand tabs jquery / simple accordion

I have query regarding Accordion tabs ..
I have used Accordion Menu plugin Below code i have used for the tabs in the page .
[accordions]
[accordion title ="about"]**Content 1** [/accordion ]
[accordion title="Home"]**Content 2** [/accordion ]
[/accordions]
The web page looks like as follows:
I want first both these tabs to be collapsed and.When clicked on ABOUT it should expand and display the content .And once clicked on Home it should collapse ABOUT tab and expand the home page
By jquery i can achieve this but i dont know which script to download and work with it..
Any ideas??
Thanks in advance
I have two different methods for simple accordion; 1st with close button, 2nd is with hover trigger.
1) Here is JsFiddle example with close button:
jQuery:
$('.content').slideUp(400);//reset panels
$('.panel').click(function() {//open
var takeID = $(this).attr('id');//takes id from clicked ele
$('#'+takeID+'C').slideDown(400);
//show's clicked ele's id macthed div = 1second
});
$('span').click(function() {//close
var takeID = $(this).attr('id').replace('Close','');
//strip close from id = 1second
$('#'+takeID+'C').slideUp(400);//hide clicked close button's panel
});​
html:
<div class="panel" id="panel1">panel1</div>
<div id="panel1C">content1
<span id="panel1Close">X</span>
</div>
<div class="panel" id="panel2">panel2</div>
<div id="panel2C">content2
<span id="panel2Close">X</span>
</div>
<div class="panel" id="panel3">panel3</div>
<div id="panel3C">content3
<span id="panel3Close">X</span>
</div>
-------
​
2) Here is JsFiddle example with hover trigger:
$('.panel').hover(function() {
var takeID = $(this).attr('id');//takes id from clicked ele
$('.content').stop(false,true).slideUp(400);//close
//used stop for prevent conflict
$('#'+takeID+'C').stop(false,true).slideDown(400);//open
//show's clicked ele's id macthed div
});​
In case you use jQuery UI Accordion, you can add simple event to your accordion.
or add event:
$( ".selector" ).bind( "accordioncreate", function(event, ui) {
$( ".selector" ).accordion( "option", "active", -1 )
});

jquery heirarchical menu design

edit:
ok, the line:
$( <?php echo("'#".$_GET['item']."'") ?> ).parent().show();
Is obviously and attempt to keep the menu open at the right place. I don't think this ever worked (got I hate working on other ppls code).
Then my current problem is how to access the <ul class="myul"> directly above the <li id="001" > using that item id=001 ??
Hi
I am trying to fix up a piece of code left to me by a now lost programmer. It works but there is a feature missing; I does not stay opened in the correct place when a menu item is selected.
Jquery:
$.swapImage(".swapImage");
$( <?php echo("'#".$_GET['item']."'") ?> ).parent().show();
$('.myul').hide();
$('.slide_ul li:not(:first-child)').hide();
$('.hideMe').click(function(){
$(this).next('ul').slideToggle('fast').siblings('ul:visible').slideUp('fast');
});
$('.myul a').click(function(e){
var url = $(this).attr('href');
var index = url.indexOf('=');
var substr = url.slice(index+1);
$('#productContainer >div').hide();
$('#productContainer').load("products/"+substr+"/product.html", function(){
$(this).fadeIn('slow');
var i = 0;
$('.slide_ul li:not(:first-child)').hide();
});
});
HTML:
<!-- Right Navigation -->
<div id="rightNav">
<div id="navMenu">
<h2 id="navMenuheader">Catalogue</h1>
<h3 class="hideMe">Widgets</h3>
<ul class="myul">
<h4 class="hideMe">Widget Coins</h2>
<ul class="myul">
<li id="001" >
The South African Widget
</li>
The result of the menu click is to injectContent into a black div in the middle of the page. Does $(document).ready(function(){ happen everytime this occurs? Otherwise I can't see why all the menu positions are updated.
I guess I need some more code to identify the place in the menu we are and leave them open. There are ants on my desk.
looks to me like the bad closing tag on
<h4 class="hideMe">Widget Coins</h2>
is your main problem, when it gets clicked on
$(this).next('ul')
fails to find a ul because it is a child instead of a sibling of the h4
changing it to
<h4 class="hideMe">Widget Coins</h4>
makes it work better, not sure if that was all you were looking for
$( <?php echo("'ul:has(#".$_GET['item'].")'");  ?> ).show();
will open every ul that has a descendant with the specified id
just using .parent() wasn't getting the top ul to show
Just had to add some jquery to reopen the relevant section of the menu after it has all been hidden. So right after the line $('.myul').hide() I reopen the menu section based on the url query ( products.php?item=001 ):
var item = <?php echo("'".$_GET['item']."'") ?>;
if (item != '')
{
item = "li#" + item;
$(item).parent().show();
$(item).parent().parent().show();
}

Categories

Resources