Multiple lavel dropdown menu set active using jQuery - javascript

When I click a menu example "C" then I want to set class active. It also should be active after reload of the page.
<ul class="nav metismenu" id="side-menu">
<li>
Dashboards
<ul class="nav nav-second-level collapse">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>
</li>
<li>
F
</li>
</ul>
To set a class active the code is :
<ul class="nav metismenu" id="side-menu">
<li class="active">
Dashboards
<ul class="nav nav-second-level collapse">
<li>A</li>
<li>B</li>
<li class="active">C</li>
<li>D</li>
<li>E</li>
</ul>
</li>
<li>
F
</li>
</ul>

First, I invite you to learn more about cookies .
So , for this case Here is Working Fiddle => jsFiddle
i used JQuery in the fiddle (dont forget to use Jquery in your sources)
ps: for security issues Snippet can't work here !!
JS :
$( document ).ready(function(){
if(typeof(getCookie("activeLi")) != "undefined" && getCookie("activeLi").length>0){
$('#side-menu ul a[ href=' + getCookie("activeLi") + ']').parent().addClass("active");
}
$("#side-menu ul a").click(function(a){
if(typeof(getCookie("activeLi")) != "undefined");
alert(getCookie("activeLi"));
removeActive();
$(this).parent().addClass("active");
setActiveCookie(this.getAttribute("href"));
});
});
function removeActive(){
$("#side-menu ul li").each(function(li){
$(this).removeClass("active");
})
}
function setActiveCookie(active){
//document.cookie="activeLi="+active;
var d = new Date();
d.setTime(d.getTime() + (30*24*60*60*1000)); // expire in 30 days
var expires = "expires="+d.toUTCString();
document.cookie="activeLi="+active+"; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
CSS :
.active a {
color: green;
}
a {
text-decoration: none;
}
HTML :
<ul class="nav metismenu" id="side-menu">
<li>
Dashboards
<ul class="nav nav-second-level collapse">
<li>A</li>
<li>B</li>
<li>C</li>
<li>D</li>
<li>E</li>
</ul>
</li>
<li>
F
</li>

Related

trigger click on next tab in jQuery

How to trigger click on next tab in jQuery, I have tried below code but not working, TIA.
var c = $('ul#tabs li').length;
var selected = parseInt($('ul#tabs li.active').index())+1;
if (c != selected) {
$("ul#tabs li:nth-child(" + selected + ")").click();
return false;
}
<div id="mytabs">
<ul class="nav nav-tabs" id="tabs">
<li class="active"><a data-toggle="tab" href="#Personal" aria-expanded="false">Personal</a></li>
<li><a data-toggle="tab" href="#Business">Business</a></li>
<li><a data-toggle="tab" href="#Documents" aria-expanded="true">Documents</a></li>
<li><a data-toggle="tab" href="#References">References</a></li>
<li><a data-toggle="tab" href="#OrderDelivery">Order & Delivery</a></li>
</ul>
</div>
I'm a bit unclear as to what's not working, but the simplified code below is all that's required to get current tab and next tab:
$(document).ready(function() {
let currentTab = $('ul#tabs li.active');
let nextTab = currentTab.next();
// Once you have the tab, click it (clicking after 2 seconds to demonstrate)
setTimeout(function() { nextTab.find("a").get(0).click()}, 2000);
// If you need to do things when a tab is clicked, create an event handler
$('a[data-toggle="tab"]').click(function(event) {
// Do something when a tab is clicked
// For example: Remove active class, and add it to active element
$('a[data-toggle="tab"]').parent().removeClass("active");
// Add active class to clicked li
$(this).parent().addClass("active");
});
});
.active a {
color: green !important;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mytabs">
<ul class="nav nav-tabs" id="tabs">
<li class="active"><a data-toggle="tab" href="#Personal" aria-expanded="false">Personal</a></li>
<li><a data-toggle="tab" href="#Business">Business</a></li>
<li><a data-toggle="tab" href="#Documents" aria-expanded="true">Documents</a></li>
<li><a data-toggle="tab" href="#References">References</a></li>
<li><a data-toggle="tab" href="#OrderDelivery">Order & Delivery</a></li>
</ul>
</div>

Detecting selected element

I have the following Javascript to operate my accordion menu.
<script src="http://thecodeplayer.com/uploads/js/jquery-1.7.1.min.js"></script>
<script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js"></script>
<script>
$(document).ready(function() {
$("#accordian a").click(function() {
var link = $(this);
var closest_ul = link.closest("ul");
var parallel_active_links = closest_ul.find(".active")
var closest_li = link.closest("li");
var link_status = closest_li.hasClass("active");
var count = 0;
closest_ul.find("ul").slideUp(function() {
if (++count == closest_ul.find("ul").length)
parallel_active_links.removeClass("active");
});
if (!link_status) {
closest_li.children("ul").slideDown();
closest_li.addClass("active");
}
})
$(".selected").parent().slideDown();
})
</script>
How do I modify the code to detect the 'selected' class and open the corresponding panel from the following html script.
<div id="accordian">
<ul>
<li>
<h3 class="mtop"> </h3>
</li>
<li>
<h3>Dashboard</h3>
<ul>
<li class="litop">Reports</li>
<li class="limid">Search</li>
<li class="limid">Graphs</li>
<li class="libot">Settings</li>
</ul>
</li>
<li>
<h3>Calendar</h3>
<ul>
<li class="litop">Current Month</li>
<li class="limid">Current Week</li>
<li class="limid">Previous Month</li>
<li class="limid">Previous Week</li>
<li class="limid">Next Month</li>
<li class="limid">Next Week</li>
<li class="limid">Team Calendar</li>
<li class="limid">Private Calendar</li>
<li class="libot">Settings</li>
</ul>
</li>
<li>
<h3>Favourites</h3>
<ul>
<li class="litop">Global favs</li>
<li class="limid selected">My favs</li>
<li class="limid">Team favs</li>
<li class="libot">Settings</li>
</ul>
</li>
<li>
<h3 class="mbot"> </h3>
</li>
</ul>
</div>
Here IS Fiddle Link - https://jsfiddle.net/p7wm4tL2/
You have old version of jquery,
Try updating your jquery version.
$(document).ready(function() {
$("#accordian a").click(function() {
var link = $(this);
var closest_ul = link.closest("ul");
var parallel_active_links = closest_ul.find(".active")
var closest_li = link.closest("li");
var link_status = closest_li.hasClass("active");
var count = 0;
closest_ul.find("ul").slideUp(function() {
if (++count == closest_ul.find("ul").length)
parallel_active_links.removeClass("active");
});
if (!link_status) {
closest_li.children("ul").slideDown();
closest_li.addClass("active");
}
})
$(".selected").parent().slideDown();
});
Once check working code here.

How can I add class on active li with JavaScript code

<ul class="nav nav-tabs">
<li onclick="this.className='active'">Home</li>
<li onclick="this.className='active'">Menu 1</li>
<li onclick="this.className='active'">Menu 2</li>
<li onclick="this.className='active'">Menu 3</li>
</ul>
How can I add active class on li tag with JavaScript. Here I am try to do it. It is working but not properly. I am doing for tabs here.
As per the comments, I guess you are expecting this:
var a = document.querySelectorAll(".nav li a");
for (var i = 0, length = a.length; i < length; i++) {
a[i].onclick = function() {
var b = document.querySelector(".nav li.active");
if (b) b.classList.remove("active");
this.parentNode.classList.add('active');
};
}
.active {
background-color: #0f9;
}
<ul class="nav nav-tabs">
<li>Home
</li>
<li>Menu 1
</li>
<li>Menu 2
</li>
<li>Menu 3
</li>
</ul>
if you have jquery
<ul class="nav nav-tabs">
<li>Home</li>
<li>Menu 1</li>
<li>Menu 2</li>
<li>Menu 3</li>
</ul>
<style>
.active {background-color: #0f9;}
</style>
<script type="text/javascript">
$("ul.nav.nav-tabs").on('click', 'li', function(){
$(this).siblings().removeClass('active');
$(this).addClass('active');
});
</script>
Vanilla JavaScript (ES6 where I tested, might work on ES5)
const elm = document.querySelector('ul');
elm.addEventListener('click', (el) => {
const elActive = elm.querySelector('.active');
if (elActive) {
elActive.removeAttribute('class');
}
el.target.setAttribute('class', 'active');
});

How to get the parent LI index and the sub LI index

Fiddle: http://jsfiddle.net/fyrx459k/
Script:
$(function() {
$('.ul1 li').click( function(e) {
e.preventDefault();
var liIndex = $(this).index('li');
console.log(liIndex);
);
});
HTML:
<ul class="ul1" id="ul1">
<li>Test</li>
<li>Test2</li>
<li>Test3
<ul class="ul2">
<li>Test3 - 1</li>
<li>Test3 - 2</li>
</ul>
</li>
<li>Test4
<ul class="ul2">
<li>Test4 - 1</li>
<li>Test4 - 2</li>
</ul>
</li>
</ul>
How can I modify the script to have the following:
When a parent LI (Test#) is clicked the console will display the index - for example, clicking on Test4 will output a 3 (fourth item)
When clicking on a sub LI (Test# - #) it will display the parent index and the child index - for example, clicking on Test3 - 1 will output 2.0 (2 being the parent LI and 0 being the first child sub LI)
This is one way of doing it:
$(function () {
$('.ul1 li').click(function (e) {
e.preventDefault();
e.stopPropagation();
var i = $(this).parentsUntil('#ul1').add(this).map(function () {
return this.tagName === 'LI' ? $(this).index() : null;
}).get().join('.');
});
});
A pretty basic solution using $(this).parents("li")
$(function() {
$('.ul1 li').click(function(e) {
e.preventDefault();
e.stopPropagation();
var liIndex = "";
var $parents = $(this).parents("li");
if ($parents.length > 0)
liIndex += ($parents.index() + 1) + ".";
liIndex += ($(this).index() + 1);
alert(liIndex);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="ul1" id="ul1">
<li>Test
</li>
<li>Test2
</li>
<li>Test3
<ul class="ul2">
<li>Test3 - 1
</li>
<li>Test3 - 2
</li>
</ul>
</li>
<li>Test4
<ul class="ul2">
<li>Test4 - 1
</li>
<li>Test4 - 2
</li>
</ul>
</li>
</ul>
I love html5 tags, so check if this solution can be useful. Otherwise you can do the same thing with the ID or whatever you prefer.
function checkIndex(element) {
deepCheck(element, '');
}
function deepCheck(element, index) {
if($(element).data('index') && $(element).is('li')) {
var newIndex = '';
if(index.length === 0) {
newIndex = 'Element indexes: ' + $(element).data('index')
} else {
newIndex = index + ' - ' + $(element).data('index');
}
deepCheck($(element).parent(), newIndex);
} else if($(element).data('root')) {
alert(index);
} else {
deepCheck($(element).parent(), index)
}
}
$(document).ready(function() {
$('a').click(function(e) {
e.preventDefault();
checkIndex(this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul data-root="true" class="ul1" id="ul1">
<li data-index="1">Test</li>
<li data-index="2">Test2</li>
<li data-index="3">Test3
<ul class="ul2">
<li data-index="1">Test3 - 1</li>
<li data-index="2">Test3 - 2</li>
</ul>
</li>
<li data-index="4">Test4
<ul class="ul2">
<li data-index="1">Test4 - 1</li>
<li data-index="2">Test4 - 2</li>
</ul>
</li>
</ul>
Use parents('li') to check if the clicked li has a li ancestor, .index() to determine the index of a li, .preventDefault() to stop the click from following the link and .stopPropagation to stop event from bubbling. This should do it:
$('#ul1 li').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
var arr = [];
arr.push( $(this).index() );
!$(this).parents('li').length ||
arr.push( $(this).parents('li').index() );
console.log( arr.reverse().join('.') );
});
$(function() {
$('#ul1 li').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
var arr = [];
arr.push( $(this).index() );
!$(this).parents('li').length ||
arr.push( $(this).parents('li').index() );
console.log( arr.reverse().join('.') );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="ul1" id="ul1">
<li>Test</li>
<li>Test2</li>
<li>Test3
<ul class="ul2">
<li>Test3 - 1</li>
<li>Test3 - 2</li>
</ul>
</li>
<li>Test4
<ul class="ul2">
<li>Test4 - 1</li>
<li>Test4 - 2</li>
</ul>
</li>
</ul>
I would suggest returning false. It removes the need to use both preventDefault and stopPropagation, and also to store the event in e.
Further, some more structured selections would be helpful here. There are only two cases to handle, where a parent element classed ul2 exits and where not. In the case it does, there needs to be two queries to determine the parents index and the current index with regards to the ul2 element. In the case where it does not, then only the relative ul1 index needs to be determined.
I included some extra elements to show the need for a more targeted approach.
$(function(){
$('.ul1 li').click(function() {
var ul2 = $(this).closest('.ul2'),
location = ul2.length > 0 ?
ul2.parent().index('.ul1 > li')+"."+ul2.find('li').index(this) :
$(this).index('.ul1 > li');
log(location);
return false;
});
});
function log(msg){ $("#result").text(msg); }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="ul1" id="ul1">
<li>Test</li>
<li>Test2</li>
<li>Test3
<ul class="ul2">
<li>Test3 - 1</li>
<li>Test3 - 2</li>
</ul>
</li>
<li>Test4
<ul class="ul2">
<li>Test4 - 1</li>
<li>Test4 - 2</li>
</ul>
</li>
</ul>
<div id="result"></div>

submenu on click must remain open

I have a vertical menu with some submenu items, and this submenu opens on click.
But the problem is that when I click on one of the submenu items, the submenu closes, whereas I want it to remain open, since when I browse on the submenu items
Here's the html:
<div class="ul_container">
<ul class="mainnav" id="nav" style="list-style:none;">
<li><a id="active" href="index.html"><strong>HOME</strong></a></li>
<li>COLLECTIONS
<ul class="subnav" id="sub1" style="display:none">
<li class="first">spring/summer 2013
<li class="first">autumn/winter 2013
<li class="first">autumn/winter 2012
<li class="first">autumn/winter 2011
</ul>
</li>
<li>PORTRAIT</li>
<li>HERITAGE</li>
<li>PRESS</li>
<li>CONTACTS</li>
</ul>
</div>
and the js
function toggleID(IDS) {
var sel = document.getElementById('nav').getElementsByTagName('ul');
for (var i=0; i<sel.length; i++) {
if (sel[i].id != IDS) { sel[i].style.display = 'none'; }
}
sel = document.getElementById(IDS);
sel.style.display = (sel.style.display != 'block') ? 'block' : 'none';
}
<div class="ul_container">
<ul class="mainnav" id="nav" style="list-style:none;">
<li><a id="active" href="#"><strong>HOME</strong></a></li>
<li>COLLECTIONS
<ul class="subnav" id="sub1" style="display:none">
<li class="first">spring/summer 2013</li>
<li class="first">autumn/winter 2013</li>
<li class="first">autumn/winter 2012</li>
<li class="first">autumn/winter 2011</li>
</ul>
</li>
<li>PORTRAIT</li>
<li>HERITAGE</li>
<li>PRESS</li>
<li>CONTACTS</li>
</ul>
$("#test").click(function() {
var sel = document.getElementById('nav').getElementsByTagName('ul');
for (var i = 0; i < sel.length; i++) {
if (sel[i].id != 'sub1') {
sel[i].style.display = 'none';
}
}
sel = document.getElementById('sub1');
sel.style.display = (sel.style.display != 'block') ? 'block' : 'none';
});
Working Example
Is your problem thay you need to remember the visibility state of the submenu once you klick on the subitems?
If so, you need to remember the state of the submenu. You can accomplish this using cookies or localstorage.
Html (just small changes, like removing onclick and fixing html)
<div class="ul_container">
<ul class="mainnav" id="nav" style="list-style:none;">
<li><a id="active" href="index.html"><strong>HOME</strong></a></li>
<li>COLLECTIONS
<ul class="subnav" id="sub1">
<li class="first">spring/summer 2013</li>
<li class="first">autumn/winter 2013</li>
<li class="first">autumn/winter 2012</li>
<li class="first">autumn/winter 2011</li>
</ul>
</li>
<li>PORTRAIT</li>
<li>HERITAGE</li>
<li>PRESS</li>
<li>CONTACTS</li>
</ul>
</div>
Javascript (using jquery with localstorage)
if(localStorage.getItem("state") == "closed") // <-- this checks closed/open state and sets subnav accordingly
$('.subnav').hide();
$('.subnav').parent().click(function () {
$(this).find('#sub1').toggle(); //<-- This toggles the menu open/close
// ** Remeber state ** //
if (localStorage.getItem("state") == "open") {
localStorage.setItem("state", "closed"); // <-- this remembers "open" after user navigates
} else {
localStorage.setItem("state", "open"); // <-- this remembers "open" after user navigates
}
// ** Remeber state ** //
});
My example uses jquery, if you have the possibility to start using it you should do so.
You can replace most of your javascript with a few lines using jquery
Check out working fiddle here
http://jsfiddle.net/urbanbjorkman/jGwnz/
Urban Bjorkman, I use your code but something is wrong...is that right?
<html>
<head>
<script type="text/javascript" >
if (localStorage.getItem("state") == "closed") // <-- this checks closed/open state and sets subnav accordingly
$('.subnav').hide();
$('.subnav').parent().click(function () {
$(this).find('#sub1').toggle(); //<-- This toggles the menu open/close
// ** Block to remeber state ** //
if (localStorage.getItem("state") == "open") {
localStorage.setItem("state", "closed"); // <-- this remembers "open" after user navigates
} else {
localStorage.setItem("state", "open"); // <-- this remembers "open" after user navigates
}
// ** Block to remeber state ** //
});
</script>
</head>
<body>
<div class="ul_container">
<ul class="mainnav" id="nav" style="list-style:none;">
<li><a id="active" href="index.html"><strong>HOME</strong></a>
</li>
<li>COLLECTIONS
<ul class="subnav" id="sub1">
<li class="first">spring/summer 2013
</li>
<li class="first">autumn/winter 2013
</li>
<li class="first">autumn/winter 2012
</li>
<li class="first">autumn/winter 2011
</li>
</ul>
</li>
<li>PORTRAIT
</li>
<li>HERITAGE
</li>
<li>PRESS
</li>
<li>CONTACTS
</li>
</ul>
</div>
</body>
</html>

Categories