Jquery remember last selected tab using local storage - javascript

i have this jquery code:
<script type="text/javascript">
$(document).ready(function() {
$(".tabLink").each(function(){
$(this).click(function(){
tabeId = $(this).attr('id');
$(".tabLink").removeClass("activeLink");
$(this).addClass("activeLink");
$(".tabcontent").addClass("hide");
$("#"+tabeId+"-1").removeClass("hide")
return false;
});
});
});
</script>
i am trying to make it so the tab is remembered if the page is refreshed by using this code:
<script type="text/javascript">
$(document).ready(function() {
$(".tabLink").each(function(){
$(this).click(function(){
localStorage.selectedTab = $(this).index() + 1;
tabeId = $(this).attr('id');
$(".tabLink").removeClass("activeLink");
$(this).addClass("activeLink");
$(".tabcontent").addClass("hide");
$("#"+tabeId+"-1").removeClass("hide")
return false;
});
});
// search for local storage
if (localStorage.selectedTab) {
$(".tabLink:eq(" + (localStorage.selectedTab - 1) + ")").click();
}
});
</script>
HTML:
<div class="tab-box">
View Customer
View Reseller Customer
View Salesman Customer
View Archived Customer
</div>
<div class="tabcontent" id="viewcustomer-1">
content...
</div>.....
it works fine, but the tabs are on multiple pages so if i go to a different page, a different tab is selected as its trying to remember the last selected tab.
how can i make it remember the last selected tab for each page?

localStorage to persist the selection :
$(document).ready(function () {
function activate(tab) {
// switch all tabs off
$(".active").removeClass("active");
// switch this tab on
tab.addClass("active");
// slide all content up
$(".content").slideUp();
// slide this content up
var content_show = tab.attr("title");
$("#" + content_show).slideDown();
}
if (localStorage) { // let's not crash if some user has IE7
var index = parseInt(localStorage['tab'] || '0');
activate($('a.tab').eq(index));
}
// When a link is clicked
$("a.tab").click(function () {
if (localStorage) localStorage['tab'] = $(this).closest('li').index();
activate($(this));
});
});

You could create a map linking URLs to selected tabs, like
tabStorage = {
"page_url_1" : 1,
"page_url_2" : 3
}
You can get the URL of current page using winow.location.
Then to save/retrieve it use JSON.stringify / JSON.parse, because localStorage only keeps key/value pairs, not objects. The key here is 'tabs', the value - a strigified representation of the map.
$(document).ready(function() {
var tabStorage = (localStorage && localStorage.tabs) ? JSON.parse( localStorage.tabs ) : {};
$(".tabLink").click(function(){
tabStorage[ window.location ] = $(".tabLink").index( this );
if(localStorage) {
localStorage.tabs = JSON.stringify( tabStorage );
}
});
if (tabStorage[ window.location ]) {
$(".tabLink").eq( tabStorage[ window.location ] ).trigger('click');
}
});

Related

Accordion does not work when loaded later via Ajax

here is my javascript Accordion code,i use multi-label accordion . first label work but does not work 2nd or 3rd label ,when i click first label accordion it does not expand .I bring in the content for the accordion dynamically using AJAX . mainly i wont show data dynamically when insert or update any data from admin panel by using setTimeInterval.
<script type="text/javascript">
var multisidetabs=(function(){
var opt,parentid,
vars={
listsub:'.list-sub',
showclass:'mg-show'
},
test=function(){
console.log(parentid);
},
events = function(){
$(parentid).find('a').on('click',function(ev){
ev.preventDefault();
var atag = $(this), childsub = atag.next(vars.listsub);
//console.log(atag.text());
if(childsub && opt.multipletab == true){
if(childsub.hasClass(vars.showclass)){
childsub.removeClass(vars.showclass).slideUp(500);
}else{
childsub.addClass(vars.showclass).slideDown(500);
}
}
if(childsub && opt.multipletab == false){
childsub.siblings(vars.listsub).removeClass(vars.showclass).slideUp(500);
if(childsub.hasClass(vars.showclass)){
childsub.removeClass(vars.showclass).slideUp(500);
}else{
childsub.addClass(vars.showclass).slideDown(500);
}
}
});
},
init=function(options){//initials
if(options){
opt = options;
parentid = '#'+options.id;
//test();
events();
}else{ alert('no options'); }
}
return {init:init};
})();
multisidetabs.init({
"id":"mg-multisidetabs",
"multipletab":false
});
// set time
function loadDoc() {
$.ajax({
url: "indexLoad.php",
success: function (data) {
v=data;
$("#demo").html(data);
}
});
return v;
}
setInterval(function () {
loadDoc();
}, 100);
"

focus on the same tab

I'm using jquery UI to create tabs. Requirement is when i select tab2 or any other tab and reload/refresh the page, focus should be on the selected tab. Please find the fiddle http://jsfiddle.net/CnEUh/500/
I have gone through many online forums but could not get the expected result.
I followed the link Set Jquery ui active tab on page load/reload , but didn't got the result.
Tried the below code :
$(document).ready(function() {
$("#tabs").tabs({active: tabs-2});
// Set active tab on page load
var SelectedTab = tabs-2;
if(tabSelectedId!=""){
$("#tabs").tabs({selected: tabSelectedId});
}
});
Please suggest how can i keep the focus on the selected tab on page reload. My fiddle http://jsfiddle.net/CnEUh/500/
You can accomplish it by using location.href
On click, just add #tab=2 and then on page load, here you can retrieve location.href and choose which tav is selected.
Add jquery.cookie.js library and the following code
$(document).ready(function() {
var $tabs = $( "#tabs" ).tabs({
activate: function(event ,ui){
$.cookie('active_tab', ui.newTab.index(), { path: '/' });
}
});
var selectedIndex=parseInt($.cookie('active_tab'));
if(selectedIndex) {
$tabs.tabs({ active: selectedIndex });
$('#tabs').find("ul:first li:nth-child(" + (selectedIndex + 1) + ")").find('a').trigger('click');
}
// set cookie on tab select
});
Or without jquery.cookie.js, pass the active tab index as a parameter
var activeTab;
var $tabs = $("#tabs").tabs({
activate: function (event, ui) {
activeTab = ui.newTab.index();
}
});
var params = {};
if (location.search) {
var parts = location.search.substring(1).split('&');
for (var i = 0; i < parts.length; i++) {
var nv = parts[i].split('=');
if (!nv[0]) continue;
params[nv[0]] = nv[1] || true;
}
}
// Now you can get the parameters you want like so:
var selectedIndex = parseInt(params.selectedIndex);
if (selectedIndex) {
$tabs.tabs({
active: selectedIndex
});
$('#tabs').find("ul:first li:nth-child(" + (selectedIndex + 1) + ")").find('a').trigger('click');
}
$('#tabs').click(function() {
window.location.href = window.location.href.replace( /[\?#].*|$/, "?selectedIndex="+activeTab );
});
Hopefully it works.
Thanks

JS popup does't works comparison operator

I have 5 link and mini preview photo and url 3 links its good link opsss and upsss is wrong when i click good link i'm going to new page when i click error link attr href change to adresError and then we have popup This only works for the first time second time click all links have a popup and should have only opsss and upsss
http://jsfiddle.net/3ptktp47/1/
Here is my code :
var nameError = [
"opsss",
"upsss",
];
$(function() {
$('#prev').hide();
$(function() {
var title_link = 'kliknij aby podejżeć';
$(".preview-link a")
.attr({title: title_link})
//.tooltip()
.click(function(){
$('.preview-link a img').css('opacity',1);
var sciezka = $(this).attr("href");
var tytul = $(this).attr("title");
var adres = $(this).text();
//alert(adres);
$(".duzy").attr({ src: sciezka, alt: tytul, style:'cursor:pointer;', href:'http://www.'+ adres,'target':'_blank'});
$('.link').html(adres).attr({href:'http://www.'+ adres,'target':'_blank'});
$('#prev').show();
function errorDomain() {
$('.link, .duzy').removeAttr('href');
$('.link, .duzy').click(function(event){
$('#popup, .popup-bg').show('slow');
$('.server_url').html(adresError).attr({href:'http://'+ adresError,'target':'_blank'});
});
};
if(adres == 'opsss.com'){
var adresError = 'x4ql.nazwa.pl/'+ nameError[0];
errorDomain();
}else if(adres == 'upsss.com' ){
var adresError = 'x4ql.nazwa.pl/'+ nameError[1];
errorDomain();
}else{
//$('#popup, .popup-bg').fadeOut();
};
$('.cancel, .popup-bg').click(function(event){
$('#popup, .popup-bg').fadeOut();
});
return false;
});
$('.close').click(function(){
$('#prev').hide();
});
$('.link').mouseover(function(){
$(this).css({style: 'color:#000;'});
});
});
});
EDITED:
Ok, I was able to handle your problem.
Your .click() event in the errorDomain() method was firing every time you clicked this square. I managed it to toggle a class on a.duzy element with toggleClass('error') in your if-statement where you check the address.
Inside your click() event, a if-statement is checking if the .duzy element has class named error with hasClass('error') , this has following result -
TRUE- your popup will be displayed
FALSE - nothing happens
I hope my answer is clear enough, but please check out the edited fiddle.
EDITED SOURCE:
Your errorDomain() Method
function errorDomain() {
$('.link, .duzy').removeAttr('href');
$('.duzy, .link').click(function (event) {
if ($(this).hasClass("error")) {
$('#popup, .popup-bg').show('slow');
$('.server_url').html(adresError).attr({
href: 'http://' + adresError,
'target': '_blank'
});
}
});
}
The if-statements
if (adres == 'opsss.com') {
var adresError = 'x4ql.nazwa.pl/' + nameError[0];
$('a.duzy').toggleClass("error");
errorDomain();
} else if (adres == 'upsss.com') {
var adresError = 'x4ql.nazwa.pl/' + nameError[1];
$('a.duzy').toggleClass("error");
errorDomain();
} else {
$('a.duzy').removeClass("error");
}
Edited fiddle

How to link to tabs with jtabs?

I added tabs to a section of my page I am working on (stridertechnologies.com/stoutwebsite/products.php)using the steps found at this website: http://code-tricks.com/create-a-simple-html5-tabs-using-jquery/
I want to link to the different tabs from the home page, but I am not sure how to do that outside of anchor names with html and that doesn't work with this, and there aren't any instructions on how to do it on the site.
It seems like there should be something really simple I can add to my javascript to detect which link they clicked on and make it the active tab.
javascript:
;(function($){
$.fn.html5jTabs = function(options){
return this.each(function(index, value){
var obj = $(this),
objFirst = obj.eq(index),
objNotFirst = obj.not(objFirst);
$("#" + objNotFirst.attr("data-toggle")).hide();
$(this).eq(index).addClass("active");
obj.click(function(evt){
toggler = "#" + obj.attr("data-toggle");
togglerRest = $(toggler).parent().find("div");
togglerRest.hide().removeClass("active");
$(toggler).show().addClass("active");
//toggle Active Class on tab buttons
$(this).parent("div").find("a").removeClass("active");
$(this).addClass("active");
return false; //Stop event Bubbling and PreventDefault
});
});
};
}(jQuery));
This answer is from a duplicated question here: https://stackoverflow.com/a/20811416/3123649.
You could pass the tab div id in the url from the link and use that to select.
Home page links from index.html:
tile
metal
Add this javascript to the tab page
<script type="text/javascript">
// To get parameter from url
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
$.extend($.expr[':'], {
attrNameStart: function (el, i, props) {
var hasAttribute = false;
$.each(el.attributes, function (i, attr) {
if (attr.name.indexOf(props[3]) !== -1) {
hasAttribute = true;
return false;
}
});
return hasAttribute;
}
});
// deselect tabs and select the tab by id
function focusTab(id) {
$("#tile").hide().removeClass("active");
$("#metal").hide().removeClass("active");
$("#shingle").hide().removeClass("active");
$("#flat").hide().removeClass("active");
$("#custom").hide().removeClass("active");
var toggle = $(id).parent().find("div");
toggle.hide().removeClass("active");
$('a:attrNameStart(data-toggle)').removeClass("active");
var id1 = getParameterByName("tabId");
var toggler = $('*[data-toggle=' + id1 + ']');
$(toggler).addClass("active");
$(id).show().addClass("active");
}
$(function() {
$(".tabs a").html5jTabs();
// Get the tab id from the url
var tabId = "#" + getParameterByName("tabId");
// Focus the tab
focusTab(tabId);
});
</script>
EDIT: Replace the original focusTab function with the edit. Also add the extend function attrNameStart. This should deselect the default active tab.
EDIT2: focusTab had a bug, it should work now
** I looked at your site and my solutions seems to be working for you. One thing I noticed. You initialize the html5jTabs() twice.
Remove the first call at the top
<script type="text/javascript">
$(function() {
$(".tabs a").html5jTabs();
});
</script>
How about something like this? Basically we are taking the value of data-toggle in our buttons, and passing it into the selector for each tab content
JS
$('a[data-toggle]').on('click', function () {
var dataToggle = $(this).data('toggle');
$('.tabContent > div').removeClass('active');
$('.tabContent > div#'+dataToggle+'').addClass('active');
});
working example:
http://jsfiddle.net/whiteb0x/VdeqY/

Dynamic Drop Down on iPhone

I'm trying to replicate the following Fiddle (http://jsfiddle.net/3UWk2/1/) on mobile (more specifically iPhone Safari) but it seems like it is not running the javascript correctly, any suggestions? Thanks!!
Here's the js:
<script>
$(document).ready(function() {
$('#00Ni0000007XPVF').bind('change', function() {
var elements = $('div.container_drop').children().hide(); // hide all the elements
var value = $(this).val();
if (value.length) { // if somethings' selected
elements.filter('.' + value).show(); // show the ones we want
}
}).trigger('change');
});
</script>
You seem to be using the cached value. hide does not return anything. So fails when you try to show them again.
var elements = $('div.container_drop').children().hide();
Supposed to be
var elements = $('div.container_drop').children();
elements.hide();
Code
$(document).ready(function() {
$('#00Ni0000007XPVF').bind('change', function() {
// cache the value
var elements = $('div.container_drop').children();
elements.hide(); // hide all the elements
var value = $(this).val();
if (value.length) { // if somethings' selected
elements.filter('.' + value).show(); // show the ones we want
}
}).trigger('change');
});

Categories

Resources