How do I store multiple divs with toggleClass in localStorage? - javascript

I'm trying to add localStorage to the toggleClass function in jQuery, so that multiple divs with the .selected css class stay .selected when reloading or closing the browser. The toggleClass seems to work, but I can't seem to get the localStorage to work. What am I doing wrong?
Here's the fiddle.
JS:
$(function(){
$('.mix').click(function() {
window.localStorage.setItem('test',$(this).toggleClass('selected'));
});
if(localStorage.getItem('test')){
$(this).toggleClass('selected');
}
});
HTML:
<div id="box" class="p001 mix">Div 1</div>
<div id="box" class="p002 mix">Div 2</div>
Thanks in advance.

You need to uniquely identify each div element, here in example I have used data-* prefixed custom attributes. On page load you need to iterate the objects and target the elements on which the value of key is set to true
HTML
<div data-id="1" class="p001 mix">Div 1</div>
<div data-id="2" class="p002 mix">Div 2</div>
Script
$(function() {
$('.mix').click(function() {
$(this).toggleClass('selected');
var lsid = 'test' + this.dataset.id;
window.localStorage.setItem(lsid, $(this).hasClass('selected'));
});
$('.mix').each(function() {
var lsid = 'test' + this.dataset.id;
if (localStorage.getItem(lsid) && localStorage.getItem(lsid) == "true") {
$(this).addClass('selected');
}
})
});
Fiddle
Note: Identifiers in HTML must be unique, thus removed id="box" and used CSS based on class

Related

Use variable as selector in function

On click, I want to get the name of the closest div and then look for all div's, that have this name attribute and add a class to them.
Here is my code:
HTML:
<div class="wrapper">
<div class="container" name="button1">
<div class="button">this is p #1</div>
</div>
</div>
<div name="button1">
somewhere else
</div>
JS:
$('.wrapper').on("click", '.button', function() {
var attrname = $(this).closest('.container').attr('name');
$("div[name=attrname]").each(function() {
$(this).addClass("classtobeadded");
});
});
But it is not working. So, how can I use the variable in here:
$("div[name=attrname]").each(function()
Here is the fiddle:
There's a few issues with your logic. Firstly the .container element does not have the name attribute, the .button does, so you don't need to use closest(). Secondly, you need to concatenate the actual name value in to the selector. Lastly div elements do not have a name attribute so the HTML is invalid. If you want to store custom meta-data on an element use a data attribute instead.
Also note that you don't need the each() loop, you can just call addClass() on the collection selected with the data-name attribute. Try this:
$('.wrapper').on("click", '.button', function() {
var attrname = $(this).data('name');
$('div[data-name="' + attrname + '"]').addClass("classtobeadded");
});
.classtobeadded {
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="button" data-name="button1">this is p #1</div>
</div>
</div>
<div data-name="button1">
somewhere else
</div>
You have to concatenate it properly,
$(`div[name=${attrname}]`).each(function() {
And by the way, when looking at your code there is no attribute available in the closest div with a class .container. Check that as well.
$("div[name=" + attrname + "]").each(function() {})
or
$(`div[name=${attrname}]`).each(function() {})

Get Div by Id and Id of Div contains multiple values jquery

I have a Div element on my HTML page, and that DIV is coming from an ASP.NET application, so the DIV ID is changing all the time but few words remain the same in that id.
For example:
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04
_NewGrid"> </div>
The only things which remains same all the time in above example are "_UWT" & "_NewGrid".
I know how to get the by Exact ID or atleast by using the 1 word in this: $( "div[id$='_UWT']" )
But I need to get this Div element by using the multiple parameters:
I need to check the "_UWT" and "_NewGrid" also.
If both words exist in the Div id, then return me the element only.
I need to get this DIV by JQuery.
I know I can set the ClientID to Static from ASP.NET, but that is not doable in my case.
Thanks.
To achieve this you can combine the 'attribute contains' selector (to find the _UWT) and the 'attribute ends with' selector (to find the _WebGrid), like this:
$('div[id*="UWT"][id$="_NewGrid"]').addClass('foo');
.foo {
color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00_ctl01_ctl00_ctl04_NewGrid">Not this one</div>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04">Not this one</div>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04_NewGrid">This one</div>
One way could be:
$('div').each(function() {
if($(this).attr('id').includes('_NewGrid') && $(this).attr('id').includes('_UWT')) {
console.log($('div').attr('id'));
$(this).css('color','red') // do whatever you want with div
}
})
Demo:
$('div').each(function() {
if($(this).attr('id').includes('_NewGrid') && $(this).attr('id').includes('_UWT')) {
console.log($('div').attr('id'));
$(this).css('color','red')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04
_NewGrid">11111</div>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04
_NewGri">222222222</div>
<div id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__ctl01_ctl00_ctl04
_NewGrid">3333333333333</div>
Try following way:
Add specific class I added here item-collection:
<div class="item-collection" id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04
_NewGrid">Div 1</div>
<div class="item-collection" id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00__UWT_ctl01_ctl00_ctl04">Div 2</div>
<div class="item-collection" id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00_ctl01_ctl00_ctl04
_NewGrid">Div 3</div>
<div class="item-collection" id="ctl00_ctl00_MainContent_DetailBody_ctl01_ctl02_ctl00_ctl01_ctl00_ctl04
_NewGrid">Div 4</div>
JS is:
var itemslist = [];
$(".item-collection").each(function(){
if($(this).attr("id").indexOf("_UWT") > -1 && $(this).attr("id").indexOf("_NewGrid")){
itemslist.push($(this))
}
})
console.log(itemslist);

jQuery check divs has a class and unwrap if no other class

I have two div's and what I am trying to do is loop through all the divs to check if the div has a class jsn-bootstrap3, I'm also trying to check to see if the div has any other classes, if it doesn't then I'd like to remove the jsn-bootstrap3 div so that the child content is whats left.
<div class="jsn-bootstrap3">
<div class="wrapper">
Div one
</div>
</div>
<div class="jsn-bootstrap3 block">
<div class="wrapper">
Div two
</div>
</div>
$('div').each(function() {
if ($(this).hasClass()) {
console.log($(this));
var class_name = $(this).attr('jsn-bootstrap3');
console.log(class_name);
}
});
jsFiddle
You can try something like
$('div.jsn-bootstrap3').removeClass('jsn-bootstrap3').filter(function () {
return $.trim(this.className.replace('jsn-bootstrap3', '')) == ''
}).contents().unwrap();
Demo: Fiddle
use the class selector to find div's with class jsn-bootstrap3 because we are not goint to do anything with others
use filter() to filter out div's with any other class
use unwrap() with contents() to remove the wrapping div

jQuery toggle 3 Div

I wanna toggle 3 div.
In the start situation I have the first div that is not trigger able for the clic because its ID.
When I click the second or third div (triggered), the DIV clicked have to become unclickable and the others 2 clickable.
I attach my live example:
http://jsfiddle.net/YV3V5/
HTML:
<div id = "not-selectable" class = "btn1">Div 1</div>
<div id = "selectable" class = "btn2">Div 2</div>
<div id = "selectable" class = "btn3">Div 3</div>
JAVASCRIPT:
$( "#selectable" ).click(function(e) {
var className = $(this).attr('class');
alert(className);
if (className == "btn1") {
$("btn1").attr("selectable","not-selectable");
$("btn2").attr("not-selectable","selectable");
$("btn3").attr("not-selectable","selectable");
} else if (className == "btn2") {
$("btn2").attr("selectable","not-selectable");
$("btn1").attr("not-selectable","selectable");
$("btn3").attr("not-selectable","selectable");
} else if (className == "btn3") {
$("btn3").attr("selectable","not-selectable");
$("btn1").attr("not-selectable","selectable");
$("btn2").attr("not-selectable","selectable");
}
});
In this situation when I click the second DIV, it should became unclickable....but nothing happens.
Thanks for you're help!
You have several errors in your code. The most important being that IDs should be unique. Secondly you are trying to assign values to attributes "selectable" and "not-selectable". These attributes do not exist.
If you lay out your markup correctly, you could do this pretty simple. I would suggest something like this:
HTML
<div class="buttons">
<div class="button">Div 1</div>
<div class="button selectable">Div 2</div>
<div class="button selectable">Div 3</div>
</div>
jQuery
$( ".buttons" ).on("click",".selectable",function(e) {
$('.button').addClass('selectable');
$(this).removeClass('selectable');
});
Can be tested here
(I've added a parent element to simplify event delegation in jQuery.)
there is no attribute called selectable for html tags.
when you write $("btn3").attr("selectable","not-selectable"); it means set the selectable attribute of btn3 to value 'not-selectable'.
also as btn3 is a class you should have written $('.btn3') instead of $('btn3')
WORKING DEMO http://jsfiddle.net/YV3V5/23/
There was a lot wrong with your code :
1) using duplicate id's : Id's must be unique , one per page. Classes do not have to be unique. So I changed around your id's and classes.
2) you should change classes with addClass/removeClass/or toggleClass
3) you shouldn't use a class your removing as the trigger of the click function, so I gave them all a same class of btn.
html :
<div id="btn1" class="not-selectable btn">Div 1</div>
<div id="btn2" class="selectable btn">Div 2</div>
<div id="btn3" class="selectable btn">Div 3</div>
css I added background of blue for selectable and red for not-selectable so easier to visualize what's happening:
.selectable {
background: blue;
}
.not-selectable {
background: red;
}
jquery :
$(document).ready(function () {
$(".btn").click(function (e) {
var id = $(this).attr('id');
if (id == "btn1") {
$("#btn1").removeClass("selectable").addClass("not-selectable");
$("#btn2").addClass("selectable").removeClass("not-selectable");
$("#btn3").addClass("selectable").removeClass("not-selectable");
} else if (id == "btn2") {
$("#btn2").removeClass("selectable").addClass("not-selectable");
$("#btn1").addClass("selectable").removeClass("not-selectable");
$("#btn3").addClass("selectable").removeClass("not-selectable");
} else if (id == "btn3") {
$("#btn3").removeClass("selectable").addClass("not-selectable");
$("#btn1").addClass("selectable").removeClass("not-selectable");
$("#btn2").addClass("selectable").removeClass("not-selectable");
}
});
});
.attr() sets the attribute to the tags. So like you would get <div non-selectable='selectable'> for that code. Here is the documentation. I would use .removeClass() and .addClass() though there might be a more efficient way.

How to "relate" elements

I was wondering how you could "relate" two HTML elements.
For example, let's say a user clicks on a selection item and I want the element "related" to that element disappear.
<div id="game1Selection">I pick team1</div>
<div id="game2Selection">I pick team2</div>
<div id="game1">This is game 1</div>
<div id="game2">This is game 2</div>
What I would want to happen is that when a user selects "game1Selection" that the div "game1" will disappear and the same thing for game2, game3, etc. I know how to do this the long way:
$('#game1Selection').click( function() {
$('#game1').toggleClass('selected');
}); //selected has the attribute display:none
How could I make two of them related so I don't have to write it the long way and just use this
jsBin demo
$('div[id$=Selection]').click(function(){
var myID = this.id.split('Selection')[0];
$('#'+myID).toggleClass('selected');
});
use the ends with selector $ and retrieve the first part of the ID name by splitting the original ID and getting the first ([0]) part of the name (gameN)
a better idea demo
But a far better example would be using this HTML:
<div>
<div class="selection">I pick team1</div>
<div class="selection">I pick team2</div>
</div>
<div class="game">This is game 1</div>
<div class="game">This is game 2</div>
and retrieve the clicked element index() and find the matching element using .eq() :
$('.selection').click(function(){
var i = $(this).index();
$('.game').removeClass('selected').eq(i).addClass('selected');
});
This will allow you to remove the already selected classes and assign it to the index-matching element.
Use classes for like behavior, and grab the number from the id.
<div id="game1Selection" class="selection">I pick team1</div>
<div id="game2Selection" class="selection">I pick team2</div>
<div id="game1" class="game">This is game 1</div>
<div id="game2" class="game">This is game 2</div>
$('.selection').click( function() {
$("#" + this.id.replace("Selection", "")).toggleClass('selected');
$('.game').not(this).removeClass('selected');
});
I prefer to use HTML5's data-* properties to make the association more explicit:
<div class="selector" data-fadetarget="game1">I pick team1</div>
<div class="selector" data-fadetarget="game2">I pick team2</div>
<div id="game1">This is game 1</div>
<div id="game2">This is game 2</div>
JavaScript:
$('.selector').click( function() {
var target = '#' + $(this).data('fadetarget');
$(target).toggleClass('selected');
});
Using this method, the associations are explicit in the markup and won't fail if things are rearranged.

Categories

Resources