localStorage onclick add/remove class - javascript

The below onclick event is working good. I want the same event should work after we reloading the page also. I tried to implement the localStorage method but not getting the expected output.
Anyone help me resolve this. Thanks in advance!
Script I have tried:
$("ul li").click(function () {
$('ul li').removeClass("one");
$(this).toggleClass("active");
localStorage.setItem('listItem', 'one');
});
$(document).ready(function(){
if(localStorage.getItem('listItem') == 'one') {
$('ul li').addClass("active");
}
});
$('ul li').click(function(){
$("ul li").removeClass("active");
$(this).addClass("active");
});
ul li.active {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>

This is the perfect solution of your problem
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style type="text/css">
ul li.active {
color: red;
}
</style>
</head>
<body id="hello">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</body>
</html>
<script type="text/javascript">
$('ul li').click(function(){
$("ul li").removeClass("active");
$('ul li').removeAttr('id');
$(this).addClass("active");
var activeElement = $(this).text();
console.log(activeElement);
localStorage.setItem('active', activeElement);
});
$(document).ready(function(){
$( "ul li" ).each(function( index ) {
if($( this ).text() == localStorage.getItem('active')){
$(this).addClass("active");
}
});
});
</script>
Here is my Fiddle link where you can check your output. Note: clear your localStorage before executing the code.

Try this Tested code. or Click here
Note: keep li id's are unique
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<style type="text/css">
ul li.active {
color: red;
}
</style>
</head>
<body >
<ul>
<li id="1">One</li>
<li id="2">Two</li>
<li id="3">Three</li>
</ul>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
$("ul li").each(function(index) {
if ($(this).attr('id') == localStorage.getItem("Activeli")) {
$(this).addClass("active");
}
});
response = JSON.parse(localStorage.getItem("wishlistID"));
$('a[data-pdtId="' + response + '"]').addClass('active')
});
$('ul li').click(function() {
$("ul li").removeClass("active");
$(this).addClass("active");
var id = $(this).attr("id");
console.log(id);
localStorage.setItem("Activeli", id); //create a localstorage
});
</script>
Hope this help you, thanks

Related

Javascript/jQuery onclick not working

i made a test.html document to test a script. Somehow it is not working and i can't get why nothing is happening. The Script is in -tags and wrapped with -tag and the css also has it´s -tags. Why shouldn't it work? Here is the code
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$('#menu li a').on('click', function() {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
</script>
<style>
.current {
text-decoration: underline;
}
ul {
list-style-type: none;
}
a {
text-decoration: none;
}
</style>
</head>
<body>
<div id="menu">
<ul>
<li><a id="about-link" class="current" href="#">ABOUT</a></li>
<li><a id="events-link" href="#">EVENTS</a></li>
<li><a id="reviews-link" href="#">REVIEWS</a></li>
<li><a id="contact-link" href="#">CONTACT</a></li>
</ul>
</div>
</body>
</html>
Because your code for binding event handler is executed before the elements is present in DOM, the event is not bound on the element.
To solve this problem, you can either
Wrap your code in ready() callback, so that your code will be executed when DOM is finished loading
Move your script to the end of <body>, so all the elements are present in DOM and you can bind the events on it
Code:
$(document).ready(function () {
$('#menu li a').on('click', function () {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
});
EDIT
You can also use load(not recommended) event callback to bind the event, but this will wait for all the resources to load completely.
If you want to use Vanilla Javascript, you can use DOMContentLoaded event on document.
you are executing the code before the DOM content is loaded. Place your code in a ready block.
You are executing the JavaScript before the <body> tag loads, which contains your <li> elements.
To solve this problem, you have three choices :
1.You can insert the JavaScript code you have written inside a $(document).ready() callback. (see http://www.w3schools.com/jquery/event_ready.asp for more information)
Code :
$(document).ready(function () {
$('#menu li a').on('click', function () {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
});
2.You can use the JavaScript's built in window.onload function. (see https://thechamplord.wordpress.com/2014/07/04/using-javascript-window-onload-event-properly/ for more information)
Code:
window.onload = function () {
$('#menu li a').on('click', function () {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
}
3.Place your <script> tag before </body> tag in your page.
Code:
<head>
<style>
.current {
text-decoration: underline;
}
ul {
list-style-type: none;
}
a {
text-decoration: none;
}
</style>
</head>
<body>
<div id="menu">
<ul>
<li><a id="about-link" class="current" href="#">ABOUT</a></li>
<li><a id="events-link" href="#">EVENTS</a></li>
<li><a id="reviews-link" href="#">REVIEWS</a></li>
<li><a id="contact-link" href="#">CONTACT</a></li>
</ul>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script>
$('#menu li a').on('click', function() {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
</script>
</body>
Note: Using $(document).ready() is a better option than using window.onload. (see window.onload vs $(document).ready() for more information)
Your code is fine. Just wrap it in DOM ready and you are good to go.
$(document).ready(function(){
$('#menu li a').on('click', function() {
$('li a.current').removeClass('current');
$(this).addClass('current');
});
})

HTML5 LocalStorage - simple issue with jQuery

I have the following code.
When I select a link, it goes from blue to red - great!
When I refresh the page, the clicked link will remain red - great!
When I click the red link, it returns to blue - great!
However, when I refresh the page that blue link goes red - not great!
I want it to remain blue when refreshed. Can someone help me out with this?
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo</title>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<style type='text/css'>
a {color: blue}
.active {color:red}
</style>
<script type='text/javascript'>
$(document).ready(function(){
$('.filters a').on('click', function() {
var data_filter = $(this).closest("a").data('filter');
if($(this).hasClass("active")) {
$(this).removeClass("active");
localStorage.setItem(data_filter,true);
}
else {
$(this).addClass("active");
localStorage.setItem(data_filter,false);
}
});
$('.filters a').each(function(){
var data_filter = $(this).closest("a").data('filter');
var checked = localStorage.getItem(data_filter);
if(checked){
$(this).addClass('active');
} else {
$(this).removeClass('active');
}
});
});
</script>
</head>
<body>
<div class="filters slide-down">
<ul class="groups inline naked right">
<li class="group">
<h3 class="text-right filter-heading trigger" data-target="#colours_filters">Colour</h3>
<ul class="naked" id="colours_filters">
<li class="filter-option">Black</li>
<li class="filter-option">Blue</li>
<li class="filter-option">Brown</li>
<li class="filter-option">Gray</li>
</ul>
</li>
<li class="group">
<h3 class="text-right filter-heading trigger" data-target="#theme_filters">Theme</h3>
<ul class="naked" id="theme_filters">
<li class="filter-option">Carefree</li>
<li class="filter-option">Decay</li>
<li class="filter-option">Dramatic</li>
<li class="filter-option">Family</li>
<li class="filter-option">Nautical</li>
</ul>
</li>
</li>
</ul>
</body>
</html>
it should be $('.filter-option a'), not $('.filters a').
localStorage setting true and false should change their places (true when it was false and vice versa).
if (checked) actually will work even for false value, because it turns out that checked is String, not Boolean. So it should be if (checked == 'true')
I also simplified some places in code.
Updated fiddle.
$(document).ready(function()
{
$('.filter-option a').on('click', function()
{
var data_filter = $(this).data('filter');
$(this).toggleClass("active");
localStorage.setItem(data_filter, $(this).hasClass("active"));
});
$('.filter-option a').each(function()
{
var data_filter = $(this).data('filter');
var checked = localStorage.getItem(data_filter);
if (checked == 'true')
{
$(this).addClass('active');
}
});
});

how to target specific css element in javascript?

I've got my code:
$(document).ready(function() {
$('#topznav ul li').click(function() {
$('#topznav').animate({
marginLeft: '10px'
}, 400);
});
});
I've got a question about the second line. It won't work. I mean, nothing really animates. The script file is loaded correctly because other functions work. What am I doing wrong here?
try this:
$(document).ready(function() {
$('#topznav ul li').click(function() {
$('#topznav').animate({
marginLeft: '+=10px'
}, 400);
});
});
Here I am posting what I got
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#topznav ul li').click(function() {
$('#topznav').animate({
marginLeft: '+=10px'
}, 400);
});
});
</script>
</head>
<body>
<div id="topznav">
<ul >
<li>
test1
</li>
<li>
test2
</li>
<li>
test3
</li>
</ul>
</div>
</body>
</html>
This works fine

JQuery setting CSS display: none when should be block

I'm looking to load a text file into a content div when the user selects a tab, the content is being inserted into the HTML file but the content div is being set to style="display: none;.
How can I get it to set the display to block whenever the relevant tab is selected and set all other contents divs to hide?
JQuery:
$(document).ready(function() {
function resetTabs() {
$("#content > div").hide();
$("#tabs a").attr("id", "");
}
var myUrl = window.location.href;
var myUrlTab = myUrl.substring(myUrl.indexOf("#"));
var myUrlTabName = myUrlTab.substring(0, 4);
(function () {
$("#content > div").hide();
$("#tabs li:first a").attr("id", "current");
$("#content > div:first").fadeIn();
$("#tabs a").on("click", function (e) {
e.preventDefault();
if ($(this).attr("id") == "current") {
return
}
else {
resetTabs();
$(this).attr("id", "current");
$($(this).attr('name')).fadeIn();
}
});
for (i = 1; i <= $("#tabs li").length; i++) {
if (myUrlTab == myUrlTabName + i) {
resetTabs();
$("a[name='" + myUrlTab + "']").attr("id", "current");
$(myUrlTab).fadeIn();
}
}
})()
});
$(document).ready(function() {
$("#tabContent1").load("test.txt");
$('a[name="#tab2"]').click(function() {
$("#tabContent2").load("test.txt");
});
});
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="CSS/common.css" />
<script src="JS/common.js"></script>
<title></title>
</head>
<body>
<nav>
<ul id="tabs">
<li>Home</li>
<li>History</li>
<li>Specifications</li>
<li>Gallery</li>
</ul>
</nav>
<div id="content">
<div id="tabContent1"></div>
<div id="tabContent2"></div>
<div id="tabContent3"></div>
<div id="tabContent4"></div>
</div>
</body>
</html>
I'm also getting the following error:
Uncaught TypeError: Object #tabContent2 has no method 'fadeIn'
i
st.event.dispatch
st.event.add.y.handle
How are tabContent and the tab connected? Try setting the name of the tabs to the actual content id's like this:
<nav>
<ul id="tabs">
<li>Home</li>
<li>History</li>
<li>Specifications</li>
<li>Gallery</li>
</ul>
</nav>
<div id="content">
<div id="tabContent1"></div>
<div id="tabContent2"></div>
<div id="tabContent3"></div>
<div id="tabContent4"></div>
</div>
This way your function $($(this).attr('name')).fadeIn(); should work a little bit better.
try this for your fadeIn
var title = $('#current').attr('name');
$(title).fadeIn()
instead of
$($(this).attr('name')).fadeIn();
(oops check edit)
Got it working using a combination of #Jaco Koster JSFiddle and the following JQuery.
$(document).ready(function () {
$("#tabContent1").load("test.txt");
$('a[name="#tabContent1"]').click(function () {
$("#tab2").removeClass('activeTab');
$("#tab3").removeClass('activeTab');
$("#tab4").removeClass('activeTab');
$(this).addClass('activeTab');
$("#tabContent1").load("test.txt");
$("#tabContent1").show();
$("#tabContent2").hide();
$("#tabContent3").hide();
$("#tabContent4").hide();
});
$('a[name="#tabContent2"]').click(function () {
$("#tab1").removeClass('activeTab');
$("#tab3").removeClass('activeTab');
$("#tab4").removeClass('activeTab');
$(this).addClass('activeTab');
$("#tabContent2").load("test2.txt");
$("#tabContent2").show();
$("#tabContent1").hide();
$("#tabContent3").hide();
$("#tabContent4").hide();
});
$('a[name="#tabContent3"]').click(function () {
$("#tab1").removeClass('activeTab');
$("#tab2").removeClass('activeTab');
$("#tab4").removeClass('activeTab');
$(this).addClass('activeTab');
$("#tabContent3").load("test3.txt");
$("#tabContent3").show();
$("#tabContent1").hide();
$("#tabContent2").hide();
$("#tabContent4").hide();
});
$('a[name="#tabContent4"]').click(function () {
$("#tab1").removeClass('activeTab');
$("#tab2").removeClass('activeTab');
$("#tab3").removeClass('activeTab');
$(this).addClass('activeTab');
$("#tabContent4").load("test4.txt");
$("#tabContent4").show();
$("#tabContent1").hide();
$("#tabContent2").hide();
$("#tabContent3").hide();
});
});

Regarding Combining Two Small Javascript Codes

Basically the question is self explanitory. I can't figure out how to combine small snippets of javascript rather than having two separate files.
The two codes are :
$(function(){
$('.navbar li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).addClass('active').siblings().removeClass('active');
}
});
});
$(function(){
$('.dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).removeClass('active')
}
});
});
Another question, is the first $(function() necessary?
Thanks for you help.
You can do this way:
Create a function and call it under it. Or, you do this:
$(function(){
$('.navbar li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).addClass('active').siblings().removeClass('active');
}
});
$('.dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).removeClass('active')
}
});
});
Some notes:
Those two functions are different.
You don't need the two function starters, $(function(){}) twice.
You can make it like this:
$(function(){
$('.navbar li, .dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
if($(this).parents(".navbar").length > 0)//this is to figure out if we are working with LI inside .navbar or not.
$(this).addClass('active').siblings().removeClass('active');
else
$(this).removeClass('active')
}
});
});
Functions are almost equal, except that you need to detect if you are working with LI from .navbar or not to select corect removeClass code.
Also, in your code first $(function() is necessary. Otherwise code inside it could be started before document is loaded. But you may put both pieces of code inside one $(function()
Full working sample, this will make the first LI of first UL red, and remove the red from the second ul LI. Your two functions are now combined.
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<title></title>
<style type="text/css">
.active {background-color:red}
ul.dropdown-menu>li.active {background-color:red}
</style>
</head>
<body>
</body>
<ul class="navbar">
<li>first</li>
<li>old</li>
<li>new</li>
<li>4</li>
</ul>
<ul class="dropdown-menu">
<li class="active">first</li>
<li>old</li>
<li>new</li>
<li>4</li>
</ul>
<script type="text/javascript">
$(function(){
$('.navbar li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).addClass('active').siblings().removeClass('active');
}
});
$('.dropdown-menu li').each(function(){
if(window.location.href.indexOf($(this).find('a:first').attr('href'))>-1)
{
$(this).removeClass('active')
}
});
});
</script>
</html>

Categories

Resources