i have this HTML Code:
<div class="tab-box">
Tab1
Tab2
Tab3
Tab4
</div>
this lists the tabs...
then each tab is like:
<div class="tabcontent" id="tab1-1">
tab1 content
</div>
<div class="tabcontent hide" id="tab2-1">
tab1 content
</div>
<div class="tabcontent hide" id="tab3-1">
tab1 content
</div>
<div class="tabcontent hide" id="tab4-1">
tab1 content
</div>
then the jquery code:
$(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();
}
});
the jquery above, i have tried to make it so it remembers the last tab selected if the page is refreshed. however, this only works with one page. if i change to view a different page with tabs, it selects a random tab as i cannot find the last one selected because it was on a different page with a different name.
how can i make it remember the last selected tab for each page?
What about cookies?
document.cookie = "tabId=" + tabeId;
then check it:
tabId = document.cookie
You can use a cookie such as document.cookie = selectedTab ,
or you can send the value of the selected tab back to the page via an ajax request such as:
var jqxhr = $.get( "example_page.php", {selectedTab: "3"} );
First, this is really bad. You are just repeating yourself.
$(".tabLink").each(function(){
$(this).click(function(){
Just use this
$(".tabLink").on("click", function() {
The rest of the method, just store the ID of the element.
// Stop the href from functioning
e.preventDefault();
// Store the tab identity in localStorage
localStorage.selectedTab = $(this).attr("id");
// Toggle the links
$(this).addClass("activeLink").siblings().removeClass("activeLink");
// Toggle the tabs
$(".tabContent").hide();
$("#" + localStorage.selectedTab + "-1").show();
});
and to show the selected tab on load
if ($(localStorage.selectedTab).length === 1) {
$(localStorage.selectedTab).click();
} else {
$("#tab1").click();
}
Try this out with my fiddle: http://jsfiddle.net/itanex/5sf8p/
Related
I am trying to save my toggleClass state of multiple dynamically generated divs and store them with LocalStorage, so they're available either on page refresh or re-visiting the page. I stuck in the middle of my code and have no more ideas.
Any solutions i found here, will not work, either they refer to a single element or they use a mix of addClass/removeClass and save state.
Saving with Cookie would be an option too.
Html:
<div id="row_parent_41" class="parent">
<div id="page_41">
<span class="showhide" id="more_2"><img src="plus.png" /></span>
</div>
<div id="holder_41" class="child">stuff goes here</div>
jQuery:
var inactiveHolder = localStorage.getItem('child') == 'true';
$(".showhide").on('click', function() {
$(this).closest(".parent").find(".child").slideToggle().toggleClass('inactiveHolder');
$('.child').toggleClass('clicked', inactiveHolder );
return false;
});
Does this code work for you?
var inactiveHolder = localStorage.getItem('child');
// set initial state
if (inactiveHolder == 'true') {
$('.child').addClass('clicked');
}
// change localstorage and class
$('.showhide').on('click', function() {
var element = $(this).closest(".parent").find(".child");
$(element).slideToggle().toggleClass('clicked');
localstorage.setItem('child', $(element).hasClass('clicked'));
return false;
});
In my mobile project I can press a menu tab (Tab2) and the tab becomes active (with background color for the active class) and the corresponding div (Div2) below will appear on the screen.
If I press another tab, that tab gets active with corr. div etc...all in all, works perfect!
But now I have the opposite problem, I want to press (in my case, swipe) a div onto my screen and have the corresponding tab above to be active (with color). e.g. swipe in Div1 on screen, Tab1 should be active and have a certain background color. Swipe in Div2, then Tab2 should be active instead etc. but can't get it to work.
Below are my li tags:
<ul class="nav nav-pills mobileNavbar">
<li onclick="swipeFunction(0)" class="col-xs-4 tab1" data-index="0">STREAM</li>
<li onclick="swipeFunction(1)" class="col-xs-4 tab2" data-index="1">CHAT</li>
<li onclick="swipeFunction(2)" class="col-xs-4 tab3" data-index="2">IDE</li>
</ul>
And my jQuery:
$('#carousel-example-generic').on('slid.bs.carousel', function() {
var savedIndex = $(this).find('.active').index();
if (savedIndex === 0){
// I want Tab1 to be active here
} else if (savedIndex == 1){
// I want Tab2 to be active here
} else if (savedIndex == 2){
// I want Tab3 to be active here
}
});
For more details into what I'm trying to build, incl. libs, images (and my previous problem, solved by "Pieter"):
Link to a section on horizontal web page
As I commented above, you are doing same thing in all the conditions. All you need to do is, to activate the navigation item by index you are getting from carousel. Try this:
$('#carousel-example-generic').on('slid.bs.carousel', function () {
var savedIndex = $(this).find('.active').index();
$('.nav-pills>li:eq(' + savedIndex + ')>a').css('background', 'yellow');
});
EDIT:
I would recommend to play with a CSS class instead of inline css. Try this:
$('#carousel-example-generic').on('slid.bs.carousel', function () {
var savedIndex = $(this).find('.active').index();
$('.nav-pills>li:eq(' + savedIndex + ')>a')
.addClass("active") // add active class to the current one
.parent().siblings() // select sibling navigation items
.removeClass("active"); // remove active class from the other navigations
});
You conveniently already have classnames "tab1", "tab2", "tab3" on the tabs, which can be matched easily based on savedIndex:
$('#carousel-example-generic').on('slid.bs.carousel', function() {
$('.nav li').removeClass('active'); // clear the old one
var savedIndex = $(this).find('.active').index();
$('.tab'+ (savedIndex+1)).addClass('active'); // add the new one
});
(I believe index() returns an integer, but if not you may need to parseInt it before adding 1.)
I'm trying to update an array when clicking on the li tag. I've been testing, testing, and unable to come up with a solution.
I have two tabs: The "Create" tab opens a container that allows you to insert paragraphs, the "Home" tab opens another container containing a "Select paragraph" button.
Problem
It won't update the values of the array when I do it for the second time. I.e., if I switch between the tabs and go on select mode again to select/deselect, it will not update the new selection, instead I get the same selection from the first time.
I've created an example so you can look at it and if there is a better way to accomplish this (which I know there is) then be my guest. Link is below the next paragraph.
Instructions
In order to select a paragraph, first you need to add a paragraph which is created on the fly, then you switch to "Home" section, click on the "Select paragraph" button, this takes you to the "Create" section on select mode. To select/deselect, click on any paragraph. When you select a paragraph, it stores its position using jQuery - index() in the "storeClass" array. Once you're done selecting paragraphs then you exit the select mode by clicking "Ok" button and it switches to "Home" section, but let's say you want to create another paragraph then you click on "Create" tab, create the paragraph, switch to "Home" tab, go on select mode and select again and switch between tabs and you will see just the first selection you made on the first time.
Here is the same example: http://jsfiddle.net/7mbhnvas/8/
HTML
<ul class="tab">
<li><a class="paragraph-tab">Create</a></li>
<li><a class="select-tab">Home</a></li>
</ul>
<div class="wrap">
<div class="create-para-cont">
<h3>Create a paragraph</h3>
<ul class="para-results">
</ul>
<div class="para-tool">
<p><textarea class="textarea"></textarea></p>
<button type="button" class="create-para-button">Create paragraph</button>
<div>
<button type="button" class="select-ok-button">OK</button>
</div>
</div>
</div>
<div class="select-para-cont">
<h3>Select Mode</h3>
<p><button type="button" class="select-para-button">Select paragraph</button></p>
</div>
</div>
jQuery
$('ul.tab li a:first').addClass('tab-active');
$('.create-para-cont').addClass('cont-active');
$('.create-para-button').on('click', function(){
$('.create-para-cont').addClass('cont-active');
var parent = $('.para-results');
var child = $('<li></li>');
var p = $('<p></p>');
var textarea = $('.textarea').val();
if($('.create-para-cont').hasClass('cont-active')){
p.text(textarea);
child.append(p);
parent.append(child);
} else {
return false
}
});
var storeClass = [];
$('.select-para-button').on('click', function(){
$('.create-para-cont').addClass('cont-select');
if($('.para-results li').length >= 1){
$('.textarea, .create-para-button').hide();
$('.select-para-cont').hide();
$('.select-tab').removeClass('tab-active');
$('.create-para-cont').show();
$('.paragraph-tab').addClass('tab-active');
$('.select-ok-button').show();
for ( var i = 0; i < storeClass.length; i = i + 1 ) {
$('.para-results').each(function( index ) {
$( this ).find( "li:eq("+ storeClass[ i ] +")" ).addClass('p-selected');
});
}
}
});
$('ul.tab li').on('click','a', function(){
if($(this).hasClass('paragraph-tab')){
$('.para-results').children('li').removeClass('p-selected');
$('.select-para-cont').hide();
$('.select-tab').removeClass('tab-active');
$('.create-para-cont').show();
$('.paragraph-tab').addClass('tab-active');
} else {
$('.create-para-cont').removeClass('cont-active');
$('.create-para-cont').hide();
$('.paragraph-tab').removeClass('tab-active');
$('.select-para-cont').show();
$('.select-tab').addClass('tab-active');
}
});
$('ul.para-results').on('click','li', function(){
if($('.create-para-cont').hasClass('cont-select')){
$(this).toggleClass('p-selected');
var selected = $('.p-selected ');
var pSelected = selected.parent().children().index(this);
storeClass.push( pSelected );
} else {
return false;
}
});
$('.select-ok-button').on('click', function(){
if($('.create-para-cont').hasClass('cont-select')){
$('.create-para-cont').removeClass('cont-select');
$('.create-para-cont').removeClass('cont-active');
$('.create-para-cont').hide();
$('.paragraph-tab').removeClass('tab-active');
$('.select-para-cont').show();
$('.select-tab').addClass('tab-active');
}
});
I would reset storeClass to a blank array when the 'OK' button is clicked, and then re-push all the correct values into it in that same click handler:
$('.select-ok-button').on('click', function(){
if($('.create-para-cont').hasClass('cont-select')) {
storeClass = []; // make it blank
$('.p-selected').each(function() {
storeClass.push($(this).index()); // push each one into the array
});
....
}
});
Then your click handler of ul.para-results would look like this:
$('ul.para-results').on('click','li', function(){
if($('.create-para-cont').hasClass('cont-select')){
$(this).toggleClass('p-selected');
} else {
return false;
}
});
Here's an updated Fiddle
I have created one page where that page contained the menu bar as tabs.
My url is mydomain.com/UI/ID=2?#about
Where with respective # the other tabs are there like photo,comment and setting.
When i reload any other tab like mydomain.com/UI/ID=2?#comment it going to about tab fraction of seconds then again it will come back to respect comment section.
Here is my code
<script type="text/javascript">
$(document).ready(function() {
$(".menu_content").hide();
var tabvalue=document.location.hash;
var activetab=$(this).find("a").attr("href")
$(".menu_content"+tabvalue).show();
//$(".menu_content:first").show();
$("ul.menu li:first").addClass("active");
$("ul.menu li").click(function() {
var activeTab = $(this).attr("rel");
$("ul.menu li").removeClass("active");
$(this).addClass("active");
$(".menu_content").hide();
$("#"+activeTab).fadeIn();
});
var firstLi = $("ul.menu li:first").attr('rel');
if('#' + firstLi !== tabvalue) {
$("ul.menu li:first").removeClass('active');
$('li[rel="'+tabvalue.substring(1)+'"]').addClass('active');
}
});
</script>
where menu_content is class name for all tabs.
Can any one guide me how to resolve this problem.
It sounds like you're running this code after the entire page has loaded therefore you're getting a flash while the HTML is rendered in it's default state, and then to the changed version once the code executes.
The nicest way to do this would be to not use a hash for this, rather have the page in the URL i.e. mydomain.com/UI/?ID=2&page=about and use server side code to render it correctly first time, and then update the url using history.pushState in JavaScript.
But if this is all a JavaScript based page, then I would say the easiest way would be to have all of the tabs 'inactive' by default, and then only add the 'active' class when you load the page (either to the hash value, or 'about' by default).
Example:
Style
<style type="text/css">
.menu_content .panel {
display:none;
}
</style>
Script
<script type="text/javascript">
$(document).ready(function() {
//if there's a hash, get it but remove the hash, or use 'about' as a default
var selectedTab = document.location.hash ? document.location.hash.replace("#", "") : "about";
$("li#" + selectedTab).addClass("active");
$("#" + selectedTab + "_panel").show();
$("ul.menu li").on('click', function() {
$("ul.menu li").removeClass("active");
$(this).addClass("active");
$(".panel").hide();
$("#" + $(this).attr("id") + "_panel").show();
});
});
</script>
HTML
<ul class="menu">
<li id="about">About</li>
<li id="comment">Comment</li>
<li id="contact">Contact</li>
</ul>
<div class="menu_content">
<div id="about_panel" class="panel"></div>
<div id="comment_panel" class="panel"></div>
<div id="contact_panel" class="panel"></div>
</div>
I have a task to highlight the menu as selected while loading the page. For that I have the following code:
$('.menuHeader').each(function () {
$(this).attr('id', 'menu' + ($(this).index() + 1));
$(this).val($(this).index() + 1);
// Set the dynamic ids for links
$(this).find('a').attr('id', 'link' + ($(this).index() + 1));
//alert('New ID : ' + $(this).find('a').attr('id'));
});
$('.menuHeader a').click(function () {
alert("a");
$('.menuHeader a').removeClass('menuHeaderActive');
$(this).parent().parent(".menuHeader").addClass('menuHeaderActive');
});
But when I select the second menu, it's refreshed and missing the selection.
HTML:
<div class="menuBar">
<div class="menuHeader ui-corner-top menuHeaderActive">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top">
<span>New Transaction</span>
</div>
</div>
How can I solve this problem?
function Home() {
window.location.href = "../../home/welcome";
}
function NewTransaction() {
window.location.href = "../../EnergyCatagory/index";
}
I think you could amend your hyperlinks to include the correct url. Then in you jQuery test the browsers current url against the hyperlinks url - if it's a match apply your menuHeaderActive class.
$(document).ready(function () {
var currentUrl = window.location.href;
var menuLink = $('.menuHeader a[href="' + currentUrl + '"]');
menuLink.parent().parent(".menuHeader").addClass('menuHeaderActive');
});
When the page reloads after one of the menu links have been clicked the script I've shown should run and $('.menuHeader a[href="' + currentUrl + '"]'); should find the menu link (hyperlink/a-tag) that matches the url the user navigated too. Then it's a case of finding the container div and adding your class.
Basically you don't add the css class when the user clicks the menu link; you have to set the css class after the page has redirected to the other page. So it's the other page that has to set the css class against the correct active menu link. There are 100's of ways to do this but based on what you've provided matching urls is the simplest.
Personally I'd have each page register a page id that corresponds to one of the menu links. Something like this...
HTML
Note the attribute data-associated-page-id added to each menuHeader div
<div class="menuBar">
<div class="menuHeader ui-corner-top" data-associated-page-id="home-welcome">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top" data-associated-page-id="energy-catagory-index">
<span>New Transaction</span>
</div>
</div>
Javascript
Added to each page
document ready handler for welcome page aka ../../home/welcome
$(document).ready(function () {
SetActiveMenuCssClass('home-welcome');
});
document ready handler for energy catagory index page aka ../../EnergyCatagory/index
$(document).ready(function () {
SetActiveMenuCssClass('energy-catagory-index');
});
function defined globally
function SetActiveMenuCssClass(pageId) {
// finds div with menuHeader class that has the attribute data-associated-page-id equal to the page id
// then sets the active class
$('.menuHeader[data-associated-page-id="' + pageId + '"]')
.addClass('menuHeaderActive');
}
If you were using a server side language like PHP then you could do something like this https://stackoverflow.com/a/11814284/81053
NOTE: The answer Chris provided works really well, but you have to actually have the link in the href of <a></a>, otherwise it will be undefined.
You could add an id to a with the link and then use
var menuLink = $('#'+currentUrl);
the code provided by Chris
(this way the page won't redirect because you clicked the link but will run the function instead)
<div class="menuBar">
<div class="menuHeader ui-corner-top menuHeaderActive">
<span>Home</span>
</div>
<div class="menuHeader ui-corner-top">
<span>New Transaction</span>
</div>
</div>
And the JS
$(document).ready(function () {
var currentUrl = window.location.href;
var menuLink = $('#'+currentUrl);
menuLink.parent().parent(".menuHeader").addClass('menuHeaderActive');
});
On a side note, if that's a different page you only have to add menuHeaderActive to the active a and remove it from the other on that specific page