Twitter Bootstrap 3 keep Tab on refresh - javascript

There where multiple Questions and solutions for the Tab container should keep the last selected tab instead of refreshing the whole page and starting in the first tab again. But the solutions i had wont work with my page. Can someone help me out?
This is my JS
<script type="javascript">
$(function() {
// for bootstrap 3 use 'shown.bs.tab', for bootstrap 2 use 'shown' in the next line
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
// save the latest tab; use cookies if you like 'em better:
localStorage.setItem('lastTab', $(this).attr('href'));
});
// go to the latest tab, if it exists:
var lastTab = localStorage.getItem('lastTab');
if (lastTab) {
$('[href="' + lastTab + '"]').tab('show');
}
});
</script>
And that's my HTML:
<ul id="myTab" class="nav nav-tabs" role="tablist" style="background-color: #3E98E4;">
<li role="presentation" class="active"><a href="#kunver" aria-controls="kunver" role="tab" data-toggle="tab" style=" border: 1px solid;
margin-top: 10%;
color: #fff;
background-color: #3C97E4;">Kunden</a></li>
<li role="presentation"><a href="#erter" aria-controls="erter" role="tab" data-toggle="tab" style=" border: 1px solid;
margin-top: 10%;
color: #fff;
background-color: #3C97E4;">Termine</a></li>
<a href="logout.php" ><button style="margin-top: 1%;margin-left:1%;
background-color: #3E98E4;
color: #fff;
border-color: #fff;" type="button" class="btn btn-default" data-toggle="tooltip" data-placement="right" title="Tooltip on right"><span class="glyphicon glyphicon-log-out"></span> Logout</button></a>
</ul>

Well I've made few modifications to your code and it will be as below:
var lastTab = localStorage.getItem('lastTab');
if (lastTab) {
$('li.active,.tab-pane.active').removeClass('active');
//remove active class from both li and tabpane since it will be by default added at page load
$('[href="' + lastTab + '"]').closest('li').addClass('active');
//add active to lastTab's parent li using closest
$(lastTab).addClass('active');
//also add active to lastTab
}
DEMO
UPDATE
Using native .tab('show') method you can do it as below but again you need to remove active class from previous default element
var lastTab = localStorage.getItem('lastTab');
if (lastTab) {
$('li.active,.tab-pane.active').removeClass('active');
$('[href="' + lastTab + '"]').tab('show');
}
UPDATED DEMO

You could just change the hash:
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
window.location.hash = $(this).attr('href');
});
The url will be updated and when the refresh button is clicked it should open the correct tab.

if you have more than one tab in the page, you can use the following code
<script type="text/javascript">
$(document).ready(function(){
$('#myTab').on('show.bs.tab', function(e) {
localStorage.setItem('activeTab', $(e.target).attr('href'));
});
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
$('#myTab a[href="' + activeTab + '"]').tab('show');
}
$('#charts-tab').on('show.bs.tab', function(e) {
localStorage.setItem('chartsactiveTab', $(e.target).attr('href'));
});
var chartsactiveTab = localStorage.getItem('chartsactiveTab');
if(chartsactiveTab){
$('#charts-tab a[href="' + chartsactiveTab + '"]').tab('show');
}
});
</script>

Related

Removing a bootstrap popover dynamically using jquery

This following works when a list item is selected and then hovered and a popover is shown. But when I try to remove popover data attributes from list tag, all the tag removes but the popover does not remove. How to remove the popover such that when an item is not selected, the popover is not shown?
/* Latest compiled and minified JavaScript included as External Resource */
// Checked list box items
$(function() {
$('.list-group.checked-list-box .list-group-item').each(function() {
// Settings
var $widget = $(this),
$checkbox = $('<input type="checkbox" class="hidden" />'),
color = ($widget.data('color') ? $widget.data('color') : "primary"),
style = ($widget.data('style') == "button" ? "btn-" : "list-group-item-"),
settings = {
on: {
icon: 'glyphicon glyphicon-check'
},
off: {
icon: 'glyphicon glyphicon-unchecked'
}
};
$widget.css('cursor', 'pointer')
$widget.append($checkbox);
// Event Handlers
$widget.on('click', function() {
$checkbox.prop('checked', !$checkbox.is(':checked'));
$checkbox.triggerHandler('change');
updateDisplay();
});
$checkbox.on('change', function() {
var id = $(this).closest('li').attr('id');
var isChecked = $checkbox.is(':checked');
if (isChecked) addPopOver(id);
else removePopOver(id);
updateDisplay();
});
function addPopOver(id) {
id = "#" + id;
$(id).attr('data-toggle', "popover");
$(id).attr('data-trigger', "hover");
$(id).attr('data-original-title', $(id).text());
$(id).attr('data-content', "(No items selected)");
$('[data-toggle=popover]').popover();
}
function removePopOver(id) {
id = "#" + id;
$(id).removeAttr("data-toggle");
$(id).removeAttr("data-trigger");
$(id).removeAttr("data-original-title");
$(id).removeAttr("data-content");
}
// Actions
function updateDisplay() {
var isChecked = $checkbox.is(':checked');
// Set the button's state
$widget.data('state', (isChecked) ? "on" : "off");
// Set the button's icon
$widget.find('.state-icon')
.removeClass()
.addClass('state-icon ' + settings[$widget.data('state')].icon);
// Update the button's color
if (isChecked) {
$widget.addClass(style + color + ' active');
} else {
$widget.removeClass(style + color + ' active');
}
}
// Initialization
function init() {
if ($widget.data('checked') == true) {
$checkbox.prop('checked', !$checkbox.is(':checked'));
}
updateDisplay();
// Inject the icon if applicable
if ($widget.find('.state-icon').length == 0) {
$widget.prepend('<span class="state-icon ' + settings[$widget.data('state')].icon + '"></span>');
}
}
init();
});
$('#get-checked-data').on('click', function(event) {
event.preventDefault();
var checkedItems = {},
counter = 0;
$("#check-list-box li.active").each(function(idx, li) {
checkedItems[counter] = $(li).text();
counter++;
});
$('#display-json').html(JSON.stringify(checkedItems, null, '\t'));
});
});
/* Check Box For item required */
.state-icon {
left: -5px;
}
.list-group-item-primary {
color: rgb(255, 255, 255);
background-color: rgb(66, 139, 202);
}
/* DEMO ONLY - REMOVES UNWANTED MARGIN */
.well .list-group {
margin-bottom: 0px;
}
.list-inline>li {
display: inline-block;
padding-right: 12px;
padding-left: 20px;
margin-bottom: 3px;
font-size: 17px;
}
#check-list-box {
padding: 10px;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<ul id="check-list-box" class="list-group checked-list-box list-inline ">
<li class="list-group-item event-item" id="venue" data-color="danger">Venue</li>
<li class="list-group-item event-item" id="catering" data-color="info">Catering</li>
<li class="list-group-item event-item" id="desserts" data-color="warning">Desserts</li>
<li class="list-group-item event-item" id="photographer" data-color="success">Photographer</li>
<li class="list-group-item event-item" id="bus" data-color="danger">Party buses</li>
<li class="list-group-item event-item" id="castles" data-color="danger">Bouncy Castles</li>
<li class="list-group-item" data-color="danger">Other</li>
<!--<input type="textbox" name ="other" >-->
</ul>
You could use .popover('destroy').
function removePopOver(id) {
id = "#" + id;
$(id).popover('destroy')
}
To destroy the shown popover you can use the following code-snippet:
function removePopOver(id) {
id = "#" + id;
$(id).popover('dispose'); // JQuery > 4.1
// $(id).popover('destroy'); // JQuery < 4.1
}
You can also remove all created popovers from your DOM via .popover class (of course each popover has its own id, so by knowing the IDs you can be more precise)
$('.popover').remove();

JQuery contextmenu Not Working On Appended Elements

JSFiddle Demo
On my mail side nav I have a custom right-click hijack of which I have just made it so you can add a new sub-folder as partly seen below;
if ($(this).hasClass('NewSubFolder')) {
if($('ul.inbox-nav li.Clicked').find('ul').length) {
$('ul.inbox-nav li.Clicked > ul').prepend("<li class='NewSubFolder'><input type='text'></li>");
} else {
$('ul.inbox-nav li.Clicked').append('<ul><li class="NewSubFolder"><input type="text"></li></ul>');
}
$("ul.inbox-nav li.Clicked").removeClass('Clicked');
}
This will add another tier where there is not one to prepend where there is, an input field. Currently you have to hit the enter key after typing something for the new folder name and then it will have worked its magic...
...However this newly appended list item does not work when you right-click it.
Hopefully this gets what you need done.
Let me know if the comments are not clear enough.
EDIT
Made an edit to combine the two on(contextmenu) calls into one function. No need for redundancy.
$(document).ready(function() {
// Trigger action when the contexmenu is about to be shown
$('#inbox-nav').on("contextmenu", 'a', function(event) {
event.preventDefault();
$('.clicked').removeClass('clicked'); //Gets rid of all other clicked elements
$(this).closest('li').addClass('clicked');
//Clicks the closest li element
var menu = ($(this).is('#inbox-nav>li>a')) ? 'MailMenuFirstTier' : 'MailMenuSecondTier';
/*This is an inline if statement, read in words it goes like this:
if this element is a direct level link, then we're going to need to use the first menu tier.
else we're going to need use the second menu tier.
*/
$("#" + menu).finish().show(100)
//dynamically calls the menu we're using.
.css({
left: event.pageX,
top: event.pageY
}); //Moves the first mail menu to the event position
});
/*
check the element to see which menut to show instead of using two different things.
*/
$(document).on('mousedown', function(e) {
//Mouse down events!
if ($('.custom-menu').is(':visible') && !$(e.target).parent().hasClass('custom-menu')) {
/*
In English:
if a custom menu is visible, AND the target of the click DOES NOT have the custom-menu class, hide the custom menu.
*/
$('.custom-menu').finish().hide();
}
if ($(e.target).parent().hasClass('custom-menu')) {
//Figure out what to do since your element is a child of the custom menu
$('.custom-menu').finish().hide();
var action = $(e.target).data('action');
//Gets our action element
var clicked = $('.clicked');
//gets the clicked element we will be working on.
switch (action) {
case 'new-folder':
//If the clicked element does not have a child ul element, add one.
$('input.rename').focusout();
//Any current input.renames will have their focus out method called
if (clicked.children('ul').length == 0) {
clicked.append($('<ul></ul>'))
}
var ul = clicked.children('ul');
//Either this child element existed before or we just made it the step before.
var input = $('<input />', {
type: 'text',
value: 'New Sub Folder',
class: 'rename',
'data-start': 'New Sub Folder',
focusout: function() {
var value = ($(this).val() == '') ? $(this).data('start') : $(this).val();
$(this).siblings('a').html(value).show();
$(this).remove();
},
autofocus: true
});
//Creates an input tag of type text, with class rename, a placeholder value, and a focusout function.
var anchor = $('<a>', {
href: '#',
css: {
display: 'none'
}
});
//Creates an anchor tag that is originally hidden
ul.append($('<li>').append([input, anchor]));
ul.find('input').click();
//Adds the (should be selected) element and the anchor
//The input element takes care of things from there
break; // end new-folder case
case 'rename-folder':
$('input.rename').focusout();
//any current input.rename items will have their focusout method called
var anchor = clicked.find('a');
//get our closest anchor of our clicked element
anchor.before($('<input />', {
type: 'text',
value: anchor.html(),
class: 'rename',
'data-start': anchor.html(),
focusout: function() {
var value = ($(this).val() == '') ? $(this).data('start') : $(this).val();
$(this).siblings('a').html(value).show();
$(this).remove();
},
autofocus: true
})).hide();
//Creates an input element, adds it before the anchor element,
//hides anchor element. the newly created input element takes care of things from there
break;
/*
ADD NEW ACTIONS HERE
*/
default:
return;
break;
}
}
}).on('keyup', 'input.rename', function(e) {
//Used for laziness. If a user hits enter in the input.rename tag, we fire the focusout target
e.preventDefault();
if (e.keyCode == 13) {
$(e.target).focusout();
}
});
});
.custom-menu {
display: none;
z-index: 1000;
position: absolute;
margin: 0;
padding: 0;
list-style: none;
overflow: hidden;
border: 1px solid #CCC;
white-space: nowrap;
font-family: sans-serif;
background: #FFF;
color: #333;
border-radius: 5px;
font-size: 12px;
}
.custom-menu li {
padding: 8px 12px;
cursor: pointer;
}
.custom-menu li:hover {
background-color: #DEF;
}
menu {
position: absolute;
}
.custom-menu .divider {
content: " ";
height: 1px;
margin: 4px 10px;
background: #929292;
}
#MailBodyList.custom-menu li.Title {
color: #929292;
}
#MailBodyList.custom-menu li.Title:hover {
background: #FFF;
cursor: default;
}
#MailBodyList.custom-menu li.ForThisSenderMore {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="inbox-nav" id="inbox-nav">
<li class="active">
<a href="javascript:;" data-type="inbox" data-title="Inbox">
<div class="Arrow"></div>Inbox
</a>
<ul>
<li>Sub-Folder 1
</li>
<li>Sub-Folder 2
</li>
<li>
Sub-Folder 3
<ul>
<li>Sub-Folder 1
</li>
<li>Sub-Folder 2
</li>
</ul>
</li>
<li>Sub-Folder 4
</li>
<li>Sub-Folder 5
</li>
</ul>
</li>
<li>
Important
</li>
<li>
Sent
</li>
<li>
<a href="javascript:;" data-type="draft" data-title="Draft"> Draft
<span class="badge badge-danger">8</span>
</a>
</li>
<li>
<a href="javascript:;" class="sbold uppercase" data-title="Trash"> Trash
<span class="badge badge-info">23</span>
</a>
</li>
<li>
<a href="javascript:;" data-type="inbox" data-title="Promotions"> Promotions
<span class="badge badge-warning">2</span>
</a>
</li>
<li>
News
</li>
</ul>
<ul id="MailMenuFirstTier" class="custom-menu">
<li>Mark All As Read</li>
<li>Empty Folder</li>
</ul>
<ul class="custom-menu" id="MailMenuSecondTier">
<li class="NewSubFolder" data-action="new-folder">New Sub-Folder</li>
<li class="Rename" data-action="rename-folder">Rename</li>
<li class="Delete" data-action="delete-folder">Delete</li>
<li>Mark All As Read</li>
<li>Empty Folder</li>
</ul>
You can use .contextmenu() to overwrite right-clic behavior.
$('.NewSubFolder').contextmenu(function() {
console.log("Right clic detected!");
});
Documentation here: https://api.jquery.com/contextmenu/
I hope it helps! :)

sidr menu close not working in chrome mobile

I am using sidr as side menu for my website. But when I open it in chrome browser at my phone. It opens when I click the button. But doesn't close when I click the button again.
If I use the dolphin browser, it just works fine.
I've created a Fiddle.. This is my code which opens and closes the menu perfectly, doesn't seem to work here.
Fiddle
JS:
$('#responsive-menu-button').sidr({
name: 'sidr',
source: '#menu',
side: 'left'
});
CSS:
#mobile-header {
display: block;
position: absolute;
top: 15px;
right: 0;
}
#mobile-header #responsive-menu-button {
height: 41px;
width: 42px;
display:block;
}
#menu {
display: none;
}
HTML:
<div id="mobile-header"> <a id="responsive-menu-button" href="#menu">THE MENU</a>
</div>
<div id="menu">
<ul>
<li><a class="menu first" href="#first">First</a>
</li>
<li><a class="menu second" href="#second"> Second</a>
</li>
<li><a class="menu third" href="#third">third</a>
</li>
<li><a class="menu fourth" href="#fourth">fourth</a>
</li>
</ul>
</div>
Also my viewport:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
The code you provided is okay. Additional JavaScript for open/close needed, as you know. This works in web and mobile versions of Google Chrome.
<script src="http://yoursite.domain.../jquery.sidr.min.js"></script>
<script>
jQuery('#responsive-menu-button').sidr({
name: 'sidr-main',
source: '.menu-main-nav-container'
});
jQuery( window ).load(function() {
if(jQuery("#sidr-main").length !== 0) {
jQuery(".sidr-class-sub-menu").hide();
jQuery( "li.sidr-class-menu-item ul.sidr-class-sub-menu" ).each(function() {
jQuery( this ).after("<div class='lnk-plus'>+</div>");
});
jQuery( ".lnk-plus" ).toggle(function() {
var id1= jQuery( this ).parent().attr("id");
jQuery("#" + id1 + " ul.sidr-class-sub-menu").show();
jQuery("#" + id1 + " .sidr-class-menu-item-has-children ul").hide();
jQuery( this ).html("-");
}, function() {
var id1= jQuery( this ).parent().attr("id");
jQuery("#" + id1 + " ul.sidr-class-sub-menu").hide();
jQuery( this ).html("+");
});
}
});
</script>
Please notice where jQuery(".sidr-class-sub-menu").hide(); is situated.

How to activate menu tab after refreshing

How can I activate a menu tab after refreshing?
Here are my code
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<style>
.menu{width: 600px; height: 25; font-size: 18px;}
.menu li{list-style: none; float: left; margin-right: 4px; padding: 5px;}
.menu li:hover, .menu li.active {
background-color: #f90;
}
</style>
</head>
<body>
<ul class="menu">
<li><a href='#'>One</a></li>
<li><a href='#'>Two</a></li>
<li><a href='#'>Three</a></li>
<li><a href='#'>Four</a></li>
</ul>
<script type="text/javascript">
var make_button_active = function()
{
//Get item siblings
var siblings =($(this).siblings());
//Remove active class on all buttons
siblings.each(function (index)
{
$(this).removeClass('active');
}
)
//Add the clicked button class
$(this).addClass('active');
}
//Attach events to menu
$(document).ready(
function()
{
$(".menu li").click(make_button_active);
}
)
</script>
Can anyone tell me How to resolve this issue ?
Just like #Johan said, store your last active tab in a localStorage or cookie. Since there is no noticeable difference in performance between the two. I suggest you use localStorage because it's much easier to use. Like this:
function make_button_active(tab) {
//Get item siblings
var siblings = tab.siblings();
//Remove active class on all buttons
siblings.each(function(){
$(this).removeClass('active');
})
//Add the clicked button class
tab.addClass('active');
}
//Attach events to menu
$(document).ready(function(){
if(localStorage){
var ind = localStorage['tab']
make_button_active($('.menu li').eq(ind));
}
$(".menu li").click(function () {
if(localStorage){
localStorage['tab'] = $(this).index();
}
make_button_active($(this));
});
});
Check out this fiddle.

Change background color on anchor in listitem when clicked

I have menu constructed by ul li with anchor tags in each. Css is applied to the anchor
and anchor:hover however I want the selected item to show that it is selected be changing the background a different color. anchor:active does not work.
I am trying javascript but not yet successful. Can this be soley done through css? I have looked at so many examples, but none actually worked right.
JAVASCRIPT
<script type="text/javascript">
function ChangeColor(obj) {
var li = document.getElementById(obj.id);
li.style.background = "#bfcbd6";
}
</script>
HTML
<div id="navigation">
<ul>
<li><a onclick="changecolor(this);" href="Default.aspx">Home</a></li>
<li><a onclick="changecolor(this);" href="View.aspx">View</a></li>
<li><a onclick="changecolor(this);" href="About.aspx">About</a></li>
</ul>
</div>
CSS - Simplified
#navigation ul {
list-style-type: none;
}
#navigation li
{
float: left;
}
#navigation a
{
background-color: #465c71;
}
#navigation a:hover
{
background-color: #bfcbd6;
}
you don't need to get id again for handling element. obj references the actual element.
<script type="text/javascript">
function ChangeColor(obj) {
obj.style.backgroundColor = "#bfcbd6";
}
</script>
Edit: And javaScript is case sensitive, so you should check your function names.
Here is a jsFiddle Demo
I have found a way to use JavaScript to solve this situation. This works for having MasterPage. Changing the id of the selected tab will then reference the css for that
selected tab only while setting the other tabs id's to null.
HTML
<div id="navbar">
<div id="holder">
<ul id="menulist">
<li><a onclick="SelectedTab(this);" href="#" id="onlink" >Home</a></li>
<li><a onclick="SelectedTab(this);" href="#" id="" >Products</a></li>
<li><a onclick="SelectedTab(this);" href="#" id="">Services</a></li>
<li><a onclick="SelectedTab(this);" href="#" id="">Gallery</a></li>
<li><a onclick="SelectedTab(this);" href="#" id="" >Contact</a></li>
</ul>
</div>
</div>
JavaScript
function SelectedTab(sender) {
var aElements = sender.parentNode.parentNode.getElementsByTagName("a");
var aElementsLength = aElements.length;
var index;
for (var i = 0; i < aElementsLength; i++)
{
if (aElements[i] == sender) //this condition is never true
{
index = i;
aElements[i].id="onlink"
} else {
aElements[i].id=""
}
}
}
Css for changing the background color after tab has been selected
#holder ul li a#onlink
{
background: #FFF;
color: #000;
border-bottom: 1px solid #FFF;
}

Categories