addClass - LocalStorage Problems - javascript

I'm working on a site and want to store a class in localStorage although I'm having some problems.
Here's the HTML:
<ul class="type">
<li id="1" class="current">Example 1</li>
<li id="2">Example 2</li>
</ul>
I have some jQuery that adds a class to one of the examples when clicked.
When the class current is active, it changes some values on the site. Basically, when you visit the site, #1 already has the class current but if I add the class the #2, I want localStorage to remember which element had the class current.
Here's what I've wrote so far of localStorage but I don't think it's right. (P.S. I'm using Modernizr).
function temp_type(){
var type = $('.type li').hasClass('current');
}
$('#1').click(function() {
$('#2').removeClass('current');
$(this).addClass('current');
if(Modernizr.localstorage) localStorage.setItem('temp_type'), $('.type li').hasClass('current');
});
$('#2').click(function() {
$('#1').removeClass('current');
$(this).addClass('current');
if(Modernizr.localstorage) localStorage.setItem('temp_type'), $('.type li').hasClass('current');
});
if(Modernizr.localstorage){
var type = localStorage.getItem('temp_type');
if(type){
$('.type li').hasClass('current');
temp_type();
}
}
Also, is there a way to test if localStorage is working or not?

This can be written in a simple way, try the below one
HTML
<ul class="type">
<li id="1">Example 1</li>
<li id="2">Example 2</li>
</ul>
<br />
Check Storage
Script
$(document).ready(function(){
$('.type li').on('click', function(event){
$('.type li').removeClass('current');
$(this).addClass('current');
if(Modernizr.localstorage){
window.localStorage['temp_type'] = $(this).attr('id'); /*Storing the id of the selected element*/
}
});
$('a').on('click', function(event){
alert(window.localStorage['temp_type']); /*Check the current storage*/
});
});
CSS
li.current {
color: red;
}
Demo JS http://jsfiddle.net/5vmBe/3/
Hope this will help you.

Related

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

add active class to main menu using javascript

I have searched a lot for adding active class to the parent menu using javascript.
I found many more examples but not a single one is working for me, below is my code
HTML
<div id="menu1" class="hmenu">
<ul>
<li>Item1
<ul>
<li>SubItem1
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</li>
</ul>
</li>
<li>SubItem2 </li>
<li>SubItem3
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</li>
</ul>
</li>
</ul>
</li>
<li>Item2</li>
<li>Item3
<ul>
<li>SubItem1
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</li>
</ul>
</li>
</ul>
</li>
</ul>
<br style="clear: left" />
</div>
My requirement is when i click on SubItem1 then both Item1 and SubItem1 should be active.
And when i click on SubSubItem1 then SubSubItem1 ,SubItem1 and Item1 should be active.
Means when click on any link then its all parent link and the same link should be active.
I have tried with this javascript code :
$(document).ready(function () {
$('.hmenu ul li ul').find('li').click(function () {
//removing the previous selected menu state
$('.hmenu').find('li.active').removeClass('active');
//adding the state for this parent menu
$(this).parents('li').addClass('active');
});
});
Actually i don't have any experience with javascript coding and unable to figure out the problem in my code.
Can anyone suggest me for the same.
The issue comes from .find('li').click().
As you use nestsed <li>, this will cause the event to be fired two times when you click on a child <li>. This causes problems. Can not you add the click() to <a> elements?
$(document).ready(function () {
$('.hmenu a').click(function () {
//removing the previous selected menu state
$('.hmenu').find('li.active').removeClass('active');
//adding the state for this parent menu
$(this).parents("li").addClass('active');
});
});
It works just fine: https://jsfiddle.net/6put8tdx/
Note that your page will be bumped to the top while clicking to a tab because of # anchor. If you want to prevent this, you may pass the event to the function .click(function (event) {...} and add event.preventDefault inside.
If you need the click target to be the LI element (as opposed to Delgan's answer)
you can use .not() over the targeted LI's parents to prevent messing with the bubbling event targets:
$(document).ready(function () {
$('.hmenu').find('li').click(function(event) {
event.preventDefault(); // Prevent page jumps due to anchors
var $par = $(event.target).parents("li"); // get list of parents
$(".hmenu .active").not( $par ).removeClass("active"); // not them
$(this).addClass('active'); // let the event propagation do the work
});
});
$(document).ready(function () {
$('.hmenu').find('li').click(function(event) {
event.preventDefault();
var $par = $(event.target).parents("li");
$(".hmenu .active").not($par).removeClass("active");
$(this).addClass('active');
});
});
.active > a{
background: gold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menu1" class="hmenu">
<ul>
<li>Item1
<ul>
<li>SubItem1
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</li>
</ul>
</li>
<li>SubItem2 </li>
<li>SubItem3
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</li>
</ul>
</li>
</ul>
</li>
<li>Item2</li>
<li>Item3
<ul>
<li>SubItem1
<ul>
<li>SubSubItem1</li>
<li>SubSubItem2</li>
</ul>
</li>
</ul>
</li>
</ul>
<br style="clear: left" />
</div>
To better understand the above
The following example works out-of-the-box, and the clicked one and all it's LI parents get the "active" class.
Why? Cause the event target is li, means any li of .hmenu - so that click is attached to any of them, and clicking the subsub LI the event will propagate to the LI parents - triggering the same click behavior (this add class)!
$(".hmenu").on("click", "li", function(){
$(this).addClass("active"); // Wow! Event propagation rulez!!
});
But we need to remove existing .active and here it gets messy...
$(".hmenu").on("click", "li", function(){
$(".active").removeClass("active"); // triggered on every event bubble :(
$(this).addClass("active"); // leaving only the main parent with active class
});
That's caused by the concurrency that happens while the event bubbles and triggers the same actions for the parent elements.
One way to prevent that concurrency would be using a setTimeout of 1ms:
$(".hmenu").on("click", "li", function(){
$(".active").removeClass("active");
setTimeout(function(){ // Let the previous finish the bubbling mess
$(this).addClass("active"); // Yey! all fine! Every LI has the active class
}, 1);
});
But here the timeout of 1ms can lead to visual "blinking" issues.
Try this:
$(function () {
$("li a")
.on("click", function () {
$(this).toggleClass("active");
$(this).closest("ul").parent().children("li a").toggleClass("active")
.parent().parent().parent().children("li a").toggleClass("active");
});
});
fiddle
Traverse from the clicked element. And use toggleClass() to avoid the mundane checking if hasclass removeClass ...

How to dynamically add a class to li item and change its background color using javascript and css

Here I have a list, what I want to do is I need to change the list ( li ) background color to different one after click on a specific list item. the thing is once it click on the link page will be redirected and refresh. please can me suggest a solution for to get this done?
<div id="main-menu">
<ul id="main-menu-list">
<li id="menu-home">Home</li>
<li id="menu-profile">My Profile</li>
<li id="menu-dashboard">My Dashboard</li>
<li id="menu-search">Search</li>
</ul>
</div>
what i did for this :
Java Script :
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()
{
$("#main-menu li").click(make_button_active);
}
)
CSS :
#main-menu-list li.active {
background: #0040FF;
}
It's a little difficult to tell exactly what you want to do, but here's some quick and dirty (and untested) code:
/// when we click on an `a` tag inside the `#main-menu-list`...
$('#main-menu-list').on('click', 'a', function(e) {
// stop the link from firing
e.preventDefault();
e.stopPropagation();
// change the list item's background to green
$(this).closest('li').addClass('myClassName').css('background-color', 'green');
// do anything else, e.g. load in pages via ajax...
});
You could use CSS to apply the green background color, instead of jQuery:
.myClassName { background-color: green; }
This will stop the page from navigating, and I don't know if that's your intention. If you want to check the currently-loaded page against the menu to find the current item, you could do this (on page load) instead:
var currentPage = window.location.pathname;
$('#main-menu-list').find('a[href^="' + currentPage + '"]').closest('li').addClass('active');
EDIT:
Your amended Javascript code can be simplified to the following:
$('#main-menu li').on('click', 'a', function (e) {
e.preventDefault();
e.stopPropagation();
// only do the following if the clicked link isn't already active
if(!$(this).closest('li').hasClass('active')) {
$(this).closest('ul').find('.active').removeClass('active');
$(this).closest('li').addClass('active');
// load in your content via ajax, etc.
}
});
JSFiddle example
For each page you can add a class to the current list item that has "where the user is"..
CSS:
.selectedItem{
background-color: orange;//whatever color your want for the selected tab..
}
Then for each of your pages,
say you're in Dashboard.html
your menu code will look like:
<div id="main-menu">
<ul id="main-menu-list">
<li id="menu-home">Home</li>
<li id="menu-profile">My Profile</li>
<li id="menu-dashboard" class="selectedItem">My Dashboard</li>
<li id="menu-search">Search</li>
</ul>
</div>
in profile.html:
<div id="main-menu">
<ul id="main-menu-list">
<li id="menu-home">Home</li>
<li id="menu-profile" class="selectedItem">My Profile</li>
<li id="menu-dashboard">My Dashboard</li>
<li id="menu-search">Search</li>
</ul>
</div>
and so on..
You need to change the background color when the document is loaded (i.e. in document.ready).
Then you need a mechanism to connect the currently loaded page to one of your list items.
$(document).ready(function(){
//get the url from the current location or in some other way that suits your solution
//perhaps use window.location.pathname
var moduleId = "dashboard" // hardcoded to dashboard to make the point :);
$("#menu-"+moduleId).css("background-color", "#ccc");
});
http://jsfiddle.net/9JaVn/1/

id manipulation in jQuery

Say I have a unordered list of item1, item2, item3, item4, each with a div around it.
<ul>
<div><li>item1</li></div>
<div class="current"><li>item2</li></div>
<div><li>item3</li></div>
<div><li>item4</li></div>
</ul>
I want that every time I click itemX, it loads itemX.html and give the div around itemX a current class attribute. Currently I'm writing 4 functions separately for four items, and they look almost the same. So how can I write a general function that just works on any itemX, loads itemX.html and changes its div's attribute? My current code seems so redundant.
Assuming that you've fixed the HTML problem(li should be sub element of ul). But still for such problem, you need to do:
$("li").click(function() {
$(".current").removeClass("current");
$(this).parent().addClass("current");
});
But the correct solution is :
HTML :
<ul>
<li>item1</li>
<li class="current">item2</li>
<li>item3</li>
<li>item4</li>
</ul>
JS:
$("li").click(function() {
$(".current").removeClass("current");
$(this).addClass("current");
});
And add some css to your li
Your HTML is invalid, which will continue to cause problems for you. Try adding css padding to your LI elements to increase the click area:
<style>
li { padding:10px; }
</style>
As to your question:
<ul id="targetElement">
<li data-contentName="item1.html">item one</li>
<li data-contentName="item2.html">item two</li>
<li data-contentName="item3.html">item three</li>
<li data-contentName="item4.html">item four</li>
</ul>
<script type="text/javascript">
$('#targetElement li').click(function(){ //for all li elements in #targetElement, do this on click
//remove the active class from the other li's
$('#targetElement li').removeClass('current');
//jQuery wrap the current li
var $this = $(this);
//add the class to the current li (the one that was clicked)
$this.addClass('current');
//get the name of the file to load
var fileToLoad = $this.data('contentName');
//then go about loading the file...
});
</script>
$("div li").on('click',function(){
$(this).siblings().removeClass("current");
$(this).load($(this).text() + ".html").closest("div").addClass("current");
});
Your question isn't clear, and your html isn't valid. so let me venture a guess at what your trying to do.
<ul class="pages"><li>item</li><li>item2</li><li>item3</li></ul>
$(function(){
$('ul.pages li').click(function(){
// load html - not user what you mean, so how ever your doing your page load.
$(this).addClass('someclass');
});
});
Is this what you where looking for?

How do i .removeClass('active') for just one of my <li> elements with jQuery?

I am having some issues figure out how i can just remove a class ="active" from a just one of my lists.
I have a navigation bar:
<div class="container">
<ul class="nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
I also have a menu within Home:
<div class="container_2">
<ul>
<li class="left-main-list active">Subject 1</li>
<ul class="list-in-list">
<li>Sub subject 1</li>
<li>Sub subject 2</li>
</ul>
<li class="left-main-list>Subject 2</li>
<li class="left-main-list>Subject 3</li>
</ul>
</div>
While i browse my menu on the home page, i want to change the the active list items class to active when clicked, so i now have this jQuery code:
$(document).ready(function() {
$('li').click(function() {
$('li').removeClass('active');
$(this).addClass('active');
});
});
This works for my menu, the class change to the current one, but it also delete my navigation bars class, which i don't want. :)
I have tried something like:
$(document).ready(function() {
$('.left-main-list').click(function() {
$('.left-main-list li').removeClass('active');
$(this).addClass('active');
});
});
I've tried '.left-main-list li' & 'li.left-main-list' without any success.
Greatful for answer to this question, and i hope my question (this time) is more accurate than my previous ones. :)
/Bill
ps: Can a sub subject AND a main subject be active at the same time, and that sub subject's class of active, be removed if you for example click another sub subject, but the main item still have it's class of active?
While i browse my menu on the home page, i want to change the the
active list items class to active when clicked
You could just target the lis within the relevant div, similar to this:
$(document).ready(function() {
var $listItems = $('div.container_2 li');
$listItems.click(function() {
$listItems.removeClass('active');
$(this).addClass('active');
});
});
DEMO - target lis within .container_2 only
Can a sub subject AND a main subject be active at the same time, and
that sub subject's class of active, be removed if you for example
click another sub subject, but the main item still have it's class of
active?
Still targeting the container you could use jQuery's parent(), similar to this:
$(document).ready(function () {
$('div.container_2 li').click(function () {
var $this = $(this);
var $children = $this.parent().find('li');
$children.removeClass('active');
$this.addClass('active');
});
});
DEMO - Using parent() to allow active menu and sub-menu but not when main menu changes
I looked at the possibility of making this more dynamic to add activation of items going up the chain when switching between sub menus located within different main menu elements.
Fixing the HTML of the nested uls whereby your nested uls are inside lis instead of just inside the upper ul you can do a fully dynamic implementation.
Assume your HTML like this:
<div class="container">
<ul class="nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
<div class="container_2">
<ul>
<li class="left-main-list active">Subject 1
</li>
<li>
<ul class="list-in-list">
<li>Sub subject 1
</li>
<li>Sub subject 2
</li>
<li>
<ul class="list-in-list">
<li>Sub subject 1
</li>
<li>Sub subject 2
</li>
</ul>
</li>
</ul>
</li>
<li class="left-main-list">Subject 2
</li>
<li class="left-main-list">Subject 3
</li>
</ul>
</div>
Now, using the following script, you can also make parents of any sub menu items active when changing from a sub menu to another which is within another main menu item, similar to this:
$(document).ready(function () {
$('div.container_2 li>a').click(function () {
var $this = $(this);
var $relatedElements = $this.parents('ul').find('li');
if($this.hasClass('active')){
return;
}
$relatedElements.removeClass('active');
$this.parent('li').addClass('active');
var $parents = $this.parents('li');
$parents.each(function(){
$(this).not($this.parent()).prev().addClass('active');
});
});
});
DEMO - Chain-like activation
I think this should have all possible examples to get you started from here.
Hope this helps.
Try this:
$("li").click(function() {
$(this.parentNode).children("li").removeClass("active");
$(this).addClass("active");
});
This will affect only the siblings of the element you click on.
$('.left-main-list').click(function() {
$('.left-main-list').removeClass('active');
$(this).addClass('active');
});
I think what you're looking for is this:
$(document).ready(function() {
$('li').click(function() {
$('li.left-main-list').removeClass('active');
$(this).addClass('active');
});
});
How about
$('li').on ('click', function (){
$(this).addClass ('active').siblings ('li').removeClass ('active');
})

Categories