jQuery and HTML, how to use localstorage in dropdown toggle menu - javascript

I have a question for you. I'm trying to use localstorage in my dropdown toggle menu. I have the following HTML code:
<li class="nav-item" id="sidebar">
<a class="sidebar-heading" href="#thirdSubmenu" data-toggle="collapse"
class="dropdown-toggle">Anagrafica</a>
<ul class="collapse list-unstyled" id="thirdSubmenu">
<li>
<a class="nav-link" href="">
<span data-feather="database"></span>
Categorie Materiale</a>
</li>
<li>
<a class="nav-link" href="">
<span data-feather="database"></span>
Sottocategorie Materiale</a>
</li>
..
I want that, when I click on Anagrafica and dropdown menu is opened, when I update my page it remains open too, storing if the dropdwon was opened or not. I'have tried the following code but does work. I'm not good at jQuery, so I hope that someone of you could help me.
Here my jQuery code:
$("#thirdSubmenu li a").on("click", function() {
var container = $(this).closest("li");
var selected_item_index = $("#thirdSubmenu li a").index(container);
localStorage.setItem("sidebar_selected", selected_item_index );
});
$(function() {
$("#thirdSubmenu li").eq(parseInt(localStorage.getItem("selected_item_index "))).addClass("active");
});

You want to index the parent <li> within it's siblings
Try changing
$("#thirdSubmenu li a").on("click", function() {
var container = $(this).closest("li");
var selected_item_index = $("#thirdSubmenu li a").index(container);
localStorage.setItem("sidebar_selected", selected_item_index );
});
To
$("#thirdSubmenu li a").on("click", function() {
// get index of parent `<li>` within it's siblings
var selected_item_index = $(this).parent().index();
localStorage.setItem("sidebar_selected", selected_item_index );
});

You can also go with JavaScript Cookies. Store a value in a cookie

Related

How to highlight active menu of a dropdown menu of bootstrap using jquery?

I want menu item to be highlighted when an item is selected in the drop down. I tried following code. Code is working if I prevent default behavior of a which I don't want, So I tried using local storage but it is not working, only page refreshes and default Home item of menu is highlighted.
Menu
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li class="dropdown">
Fire & Water <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Water Damage</li>
<li>Fire Damage</li>
<li>Storm Damage</li>
<li>Commercial Restoration</li>
</ul>
</li>
<li class="dropdown">
Mold <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Mold Remediation</li>
<li>What is Black Mold?</li>
<li>Mold "Removal" vs Remediation</li>
<li>Commercial Mold Remediation</li>
</ul>
</li>
</ul>
This is Working
$(document).ready(function(){
$(".dropdown-menu li a").click(function(e){
e.preventDefault();
var hrefs = $(this).attr('href');
alert("hrefs : " + hrefs);
$("li").removeClass('active');
$('a[href="' + hrefs + '"]').parents('li').addClass('active');
});
});
This is not working
$(document).ready(function(){
$(".dropdown-menu li a").click(function(){
var hrefs = $(this).attr('href');
alert("hrefs : " + hrefs);
localStorage.setItem('activeTab', hrefs);
var activeTab = localStorage.getItem('activeTab');
$("li").removeClass('active');
alert("activeTab : " + activeTab);
$('a[href="' + activeTab + '"]').parents('li').addClass('active');
});
});
I think, you have to apply active class on page load event not in click event. your code should be something like as below
$(document).ready(function(){
// activate left navigation based on current link
var current_url = window.location;
$('.dropdown-menu li a').filter(function () {
return this.href == current_url;
}).last().parents('li').addClass('active');
});
On every page load, you have to filter out link of current page from your navigation bar and then apply class active in parent. I have posted code for your explanation purpose you have to modify as per your HTML code structure.
Hope, this will work :)

Add class to active menu items with internal anchors

I have a page with a list of menu items consisting of internal anchors. I'm trying to add an .active class to the selected item. It seems to work on load but when clicking a new item in that same page it doesn't.
When clicking a new menu item, I would like to remove all other active classes and add this class to the clicked item.
Sounds pretty simple, but I can't make it work.
I created this Fiddle, but it doesn't show the issue correctly, since I can't add hashes to the url.
However, maybe someone can point me in the right direction.
JS:
function setActiveLinks() {
var current = location.pathname;
$('.bs-docs-sidenav li a').each(function() {
var $this = $(this);
// Get hash value
var $hash = location.href.substr(location.href.indexOf('#') + 1);
if ($this.attr('href') == '#' + $hash) {
$this.parent().addClass('active');
}
})
}
setActiveLinks();
$('#leftmenu li a').click(function() {
$('#leftmenu li').removeClass('active');
setActiveLinks();
});
HTML:
<ul class="nav bs-docs-sidenav">
<li>
Download
</li>
<li class="active">
What's included
<ul class="nav">
<li class="active">Precompiled</li>
<li>Source code</li>
</ul>
</li>
<li>
Compiling CSS and JavaScript
<ul class="nav">
<li>Installing Grunt</li>
<li>Available Grunt commands</li>
<li>Troubleshooting</li>
</ul>
</li>
</ul>
Thanks. :-)
You have wrong selector to bind click event on anchor element. also you don't need to call setActiveLinks() function(which sets class based on href) here.
You can use context of clicked anchor element to traverse to parent li and add class active in it:
var $navLIs = $('.nav li')
$navLIs.find('a').click(function() {
$navLIs.removeClass('active');
$(this).parent().addClass('active');
});
Working Demo

Change and keep active class in navigation menu, on click and refresh

I am trying to create a navigation menu using css and js. I have styled the necessary classes, and nav works with js animation, however I am having a problem changing the class of li to active onclick by the user, and saving this in local storage so that it remains when the page refreshes.
This is the code that I have now:
http://codepen.io/anon/pen/wfpti
Javascript:
var foundActive = false, activeElement, linePosition = 0, menuLine = $("#navmenu #menu-line"), lineWidth, defaultPosition, defaultWidth;
$("#navmenu > ul > li").each(function() {
if ($(this).hasClass('active')) {
activeElement = $(this);
foundActive = true;
}
});
Html:
<div id='navmenu'>
<ul>
<li class='active'><a href='link1.php'>link1</a></li>
<li><a href='link2.php'>link2</a></li>
<li><a href='link3.php'>link3</a></li>
<li><a href='link4.php'>link4</a></li>
<li><a href='link5.php'>link5</a></li>
<li><a href='link6.php'>link6</a></li>
<li><a href='link7.php'>link7</a></li>
</ul>
</div>
What I would like to achieve is that when I press, for example, "link3" is that it goes to link3.php, and the navigation menu then shows link3 as the active class link, while removing the previous active class for link1.
Just try to add class on click event this function will stop your active links. this may works for you. if you want to add active class after refreshing a page then store it to javascript cookies.
$("#navmenu > ul > li").click(function()
{
$(this).closest('ul').find('li').each(function()
{
$(this).removeClass('active');
});
$(this).addClass('active');
defaultWidth = lineWidth = activeElement.width();
defaultPosition = linePosition = activeElement.position().left;
menuLine.css("width", lineWidth);
menuLine.css("left", linePosition);
});

how to set active class to nav menu from twitter bootstrap

I'm new to the twitter bootstrap. Using there navigation menus . I'm trying to set active class to selected menu.
my menu is -
<div class="nav-collapse">
<ul class="nav">
<li id="home" class="active">Home</li>
<li>Project</li>
<li>Customer</li>
<li>Staff</li>
<li id="broker">Broker</li>
<li>Sale</li>
</ul>
</div>
I tried following thing after googling on this that i have to set active class on each page from menu like as--
<script>
$(document).ready(function () {
$('#home').addClass('active');
});
</script>
but problem for above is that i set home menu selected by default. Then it always get selected. Is there any other way to do this ? , or which i can generalize and keep my js in layout file itself?
After executing application my menu looks -
after clicking on other menu item i get following result-
And i added following scripts on Index view and Broker view ---
<script>
$(document).ready(function () {
$('#home').addClass('active');
});
</script>
<script>
$(document).ready(function () {
$('#broker').addClass('active');
});
</script>
respectively.
You can use this JavaScript\jQuery code:
// Sets active link in Bootstrap menu
// Add this code in a central place used\shared by all pages
// like your _Layout.cshtml in ASP.NET MVC for example
$('a[href="' + this.location.pathname + '"]').parents('li,ul').addClass('active');
It'll set the <a>'s parent <li> and the <li>'s parent <ul> as active.
A simple solution that works!
Original source:
Bootstrap add active class to li
it is a workaround. try
<div class="nav-collapse">
<ul class="nav">
<li id="home" class="active">Home</li>
<li>Project</li>
<li>Customer</li>
<li>Staff</li>
<li id="demo">Broker</li>
<li id='sale'>Sale</li>
</ul>
</div>
and on each page js add
$(document).ready(function () {
$(".nav li").removeClass("active");//this will remove the active class from
//previously active menu item
$('#home').addClass('active');
//for demo
//$('#demo').addClass('active');
//for sale
//$('#sale').addClass('active');
});
I had the same problem... solved it by adding the code shown below to the Into "$(document).ready" part of my "functions.js" file which is included in every page footer. It's pretty simple. It gets the full current URL of the displayed page and compares it to the full anchor href URL. If they are the same, set anchor (li) parent as active. And do this only if anchor href value is not "#", then the bootstrap will solve it.
$(document).ready(function () {
$(function(){
var current_page_URL = location.href;
$( "a" ).each(function() {
if ($(this).attr("href") !== "#") {
var target_URL = $(this).prop("href");
if (target_URL == current_page_URL) {
$('nav a').parents('li, ul').removeClass('active');
$(this).parent('li').addClass('active');
return false;
}
}
}); }); });
For single-page sites where the menu items simply jump down to other sections of the page, this simple solution works for me:
$('.nav li').on('click', function(){
$('.nav li').removeClass('active');
$(this).addClass('active');
});
You could add a diffrent class onto the BODY tag on each page e.g. on the homepage you could have this:
<body class="nav-1-on">
Then this css:
.nav-1-on .nav-1 a, .nav-2-on .nav-2 a, .nav-3-on .nav-3 a, .nav-4-on .nav-4 a {
// set your styles here
}
The NAV element:
<ul>
<li class="nav-1">Home</li>
<li class="nav-2">Services</li>
<li class="nav-3">About</li>
<li class="nav-4">Contact</li>
</ul>
#
Alternatively you could place a class on the BODY on each page and then grab that via jQuery and add the .active class to the correct nav item based on that tag.
<div class="nav-collapse">
<ul class="nav">
<li class="home">Home</li>
<li class="Project">Project</li>
<li class="Customer">Customer</li>
<li class="Staff">Staff</li>
<li class="Broker">Broker</li>
<li class="Sale">Sale</li>
</ul>
</div>
then for each page you add this:
//home
$(document).ready(function () {
$('.home').addClass('active');
});
//Project page
$(document).ready(function () {
$('.Project').addClass('active');
});
//Customer page
$(document).ready(function () {
$('.Customer').addClass('active');
});
//staff page
$(document).ready(function () {
$('.Staff').addClass('active');
});
<div class="nav-collapse">
<ul class="nav">
<li class="home">Home</li>
<li class="Project">Project</li>
<li class="Customer">Customer</li>
<li class="Staff">Staff</li>
<li class="Broker">Broker</li>
<li class="Sale">Sale</li>
</ul>
</div>
$('ul.nav>li.home>a').click(); // first. same to all the other options changing the li class name
For single page sites, the following is what I used. It not only sets the active element based on what's been clicked but it also checks for a hash value within the URL location on initial page load.
$(document).ready(function () {
var removeActive = function() {
$( "nav a" ).parents( "li, ul" ).removeClass("active");
};
$( ".nav li" ).click(function() {
removeActive();
$(this).addClass( "active" );
});
removeActive();
$( "a[href='" + location.hash + "']" ).parent( "li" ).addClass( "active" );
});
For those using Codeigniter, add this below your sidebar menu,
<script>
$(document).ready(function () {
$(".nav li").removeClass("active");
var currentUrl = "<?php echo current_url(); ?>";
$('a[href="' + currentUrl + '"]').parents('li,ul').addClass('active');
});
</script>
(function (window) {
bs3Utils = {}
bs3Utils.nav = {
activeTab: function (tabId) {
/// <summary>
/// 设置需要展现的tab
/// </summary>
/// <param name="tabId"></param>
$('.nav-tabs a[href="#' + tabId + '"]').tab('show');
}
}
window.bs3Utils = bs3Utils;
})(window);
example:
var _actvieTab = _type == '0' ? 'portlet_tab2_1' : 'portlet_tab2_2';
bs3Utils.nav.activeTab(_actvieTab);
<ul class="nav nav-tabs">
<li class="active">
箱-单灯节点
</li>
<li>
箱-灯组节点
</li>
</ul>
$( ".nav li" ).click(function() {
$('.nav li').removeClass('active');
$(this).addClass('active');
});
check this out.
I am using Flask Bootstrap.
My solution is a little bit simpler because my template already receives the option or choice as a parameter from Flask.
var choice = document.getElementById("{{ item_kind }}");
choice.className += "active";
First line, js code gets the element. So, you should identify each of the elements with a id. I'll show an example below.
Second line, you add the class active.
You can see html ids below.
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a id="speed" href="{{ url_for('list_gold_per_item',item_kind='speed',level='2') }}">
<h2>Speed</h2>
</a>
</li>
<li>
<a id="life" href="{{ url_for('list_gold_per_item',item_kind='life',level='3') }}">
<h2>Life</h2>
</a>
</li>
</ul>
</div>
I just added a custom class to the ul section named target-active
<ul class="nav navbar-nav target-active">
<li>HOME</li>
<li>FIND A TRUCK</li>
<li>OUR SERVICES</li>
<li>ABOUT US</li>
</ul>
If each li tags click get a new page from different place or same place, no need to add jquery removeClass function.
Add simple one line jquery code to each page to get your desired result
1st link page
$(function(){
$(".target-active").find("[href='/']").parent().addClass("active");
});
2nd link page
$(function(){
$(".target-active").find("[href=find-truck]").parent().addClass("active");
});
3rd link page
$(function(){
$(".target-active").find("[href=our-service]").parent().addClass("active");
});
4th link page
$(function(){
$(".target-active").find("[href=about-us]").parent().addClass("active");
});

jQuery Mobile buttons not working as expected

<ul data-role="listview">
<li>Facebook</li>
<li>Google</li>
<li>Apple</li>
</ul>
$(document).bind('pagebeforecreate',function(){
$('form ul li').each(function(){
$(this).html('<a role="button" data-icon="plus" data-iconpos="left">'+$(this).text()+'</a>');
});
});
The code above should change the listview into a list of buttons with a plus icon on the left side. However, it isn't working for me. The <a...></a> is being inserted correctly, but the icon isn't showing up correctly. This default icon is still being displayed. How can I fix this?
In addition to #patrick's reply above, you also need to initialize the button widget after attaching it to the document. Try this,
$(document).bind('pageshow',function(){
$('ul li').each(function(){
var $this = $(this);
$this.html('<a data-role="button" data-icon="plus" data-iconpos="left">'+$this.text()+'</a>');
var $btn = $('a', $this);
$btn.button();
});
});
According to the jQuery mobile docs a data-role="button" attribute is required to style any anchor link as a button.
In your code you have:
<a role="button"
This is incorrect.
You need to change this to:
<a data-role="button"
So your whole code will now be:
<ul data-role="listview">
<li>Facebook</li>
<li>Google</li>
<li>Apple</li>
</ul>
$(document).bind('pagebeforecreate',function(){
$('form ul li').each(function(){
$(this).html('<a data-role="button" data-icon="plus" data-iconpos="left">'+$(this).text()+'</a>');
});
});

Categories