Trouble saving current state of css class in local storage - javascript

I am using two buttons to toggle css classes that either show or hide a background. I would like to save the current state of each class in local storage and display (or not display) them when the user returns. I have made an attempt with the wrapping class in this jsFiddle, but I don't have it working yet:
http://jsfiddle.net/eqrk6fak/1/
Setting it like so:
$("#switch2").click(function() {
wrap.fadeToggle(600);
if($('div').hasClass(wrap)){
localStorage.setItem('background', wrap);
}
});
And then trying to get it when the user returns:
$(document).ready(function(){
var background = localStorage.getItem('background');
if(background !== ''){
$('#wraping').addClass(background);
}
});
Any help would be appreciated. Thanks!

The problem is in the following line:
$('div').hasClass(wrap)
Reviewing your JSFiddle code, at that point wrap is a jQuery result:
var wrap = $(".wraping");
According to the documentation, jquery.hasClass receives a className which should be a String.

Related

To-Do List with localStorage

I have made a simple to-do list. But I want to make a list element have a text-decoration = line-through
When I click the button, the list item will be styled with a line-through and it will remain line-through even when I refresh the page or come back to it in a new request (I think local storage is needed).
I thought I could add a class with javascript but I couldn't find how I can do that with local storage.
Below is what I have tried:
HTML:
<ul id="a2">
<li>Make a ramen</li>
</ul>
<button type="button" id="ka" onclick="laylay()" class="" name="button">A</button>
CSS:
.done {
text-decoration: line-through;
}
JS:
function laylay() {
var as = document.getElementById("a2");
as.classList.add("done");
}
If you want to store the state of the list across session or requests and you have no backend storage for the list (meaning it is all stored on the client aka via the browser) you will need to use local storage.
Try this.
localStorage.setItem('a2', 'done');
Then when the page loads get the item from local storage and set the needed class.
localStorage.getItem('a2');
You will need to have an event that fires as soon as the document is ready that will look into your local storage and see if it finds the record it needs and if it does it updates the CSS style.
window.onload(function() {
var itemStyle = localStorage.getItem('a2');
var as = document.getElementById("a2");
as.classList.add(itemStyle);
}
This is not a very scalable solution but for your learning and simple example, it will work.
Try taking the HTML of the element, document.querySelector("#a2").innerHTML;, and saving it as a string in localStorage. And when you need to load it again, try checking if it exists in localStorage, then the string will be set as the innerHTML of #a2
You should have array of object stored in localstorage that look like something this:
[
{todo:'Do something', complete:false},
{todo:'Do something', complete:false},
]
Then when you render todos to page you make conditions based on object what styling your todo should have.
Eg.
let todos=localStorage.getItem('todos');
todos.map(item=>{
if(item.complete){
//code to add this item to page and put .style.textDecoration='line-trough'
}
else{
//code to put item to page
}
})
in order to store this kind of object you will need to stringify it when u set it and than when u use it u need to parse it.You can google it out how to do it.
If you are using some framework it will be much easier to render it on page the way you want, but it can be done with js it is just longer code.
Eg.
//Way to get items from localStorage
let todos=JSON.parse(localStorage.getItem("todos") || "[]");
//Way to set item
localStorage.setItem("todos",JSON.stringify(todos));

Hide dynamic JS buttons based on a var value

I am having a similar problem to this: Hide dynamically added buttons based on an if statement. With a JS mod for A Dark Room I am working on to increase my JS skills. Neither of these snippets are mine, and both are working perfectly.
This is the code snippet to create the buttons:
build: function(buildBtn) {
var thing = $(buildBtn).attr('buildThing');
if($SM.get('game.temperature.value') <= Room.TempEnum.Cold.value) {
Notifications.notify(Room, _("builder just shivers"));
return false;
}
This snippet makes sure that buttons stay visible, but I would like to change it so that when a max value is met the button is hidden.
//show button if one has already been built
if($SM.get('game.buildings["'+thing+'"]') > 0){
Room.buttons[thing] = true;
return true;
}
Hiding and showing elements is typically done through a class. Have a css class like this
.hidden {
display : none'
}
Then in your javascript, add or remove hidden class according to your condition
if(condition) {
$(element).addClass('hidden');
} else {
$(element).removeClass('hidden');
}
It's hard to suggest because there isn't enough context. The snippet you show may not just be exclusively responsible for controlling the visibility of the button (despite the inline comment saying it is). As a result the following suggestion may not work and more information on what you're trying to do and more code would be needed.
If you have access to modify the snippet then you can include the max value there. If the max value is a variable (i.e myCustomMaxValue) and it's in scope then my best guess would be to add it here:
var myCustomMaxValue = 88;
var someOtherVariableInScope = 50
//show button if one has already been built
if($SM.get('game.buildings["'+thing+'"]') > 0){
//add your condition here and yield true/false
var myCustomCondition = someVariableInScope > myCustomMaxValue;
Room.buttons[thing] = myCustomCondition;
return myCustomCondition;
}
I would suggest the debug; keyword. Place it in the snippet and open your browsers' developer tools and its debugger will get hit. You can then inspect the variables in scope and verify the snippet is in fact responsible for dynamically showing and hiding the button.
//show button if one has already been built
if($SM.get('game.buildings["'+thing+'"]') > 0){
debug;
Room.buttons[thing] = myCustomCondition;
return myCustomCondition;
}

Javascript Help on Dropdown filter

I was able to find a solution on Stackoverflow that display HTML "li" elements based on a filter (see attachement). Essentially based on css class'es defined in HTML elements, it populates the drop down list that you can select from.
I would like to be modify javascript below so that when you navigate to one of the "li" elements pages (as seen here: https://jsfiddle.net/quwfmepL/2/ e.g. Note: Chose one Test1 element and it goes to the page1.html page) ..but when you hit the back button on the page1.html to page where filter resides, it doesn't remember last filter choice. As it does now, you are required to filter same choice again. I think what I need to do is look at the browser history, but not sure if there is an easier option. I was hoping it could be in the format of query string or like.
<script type="text/JavaScript">
$(document).ready(function() {
var $tagList = $('#tag-list'),
optionArr = [];
$("#demo-list li a").each(function(index, item) {
$.each($(this).attr('class').split(' '), function(i, option){
if ($.inArray(option, optionArr) == -1) {
$tagList.append('<option value="'+option+'">'+option.replace('-', ' ').replace('_', ' ')+'</option>');
optionArr.push(option);
}
});
});
// Look at the URL for filter and modify here #
$tagList.on('change', function() {
var selection = $tagList.val();
if (selection == "all") {
$('#demo-list li a').show();
} else {
$('#demo-list li a').hide();
$('#demo-list li a.'+selection).show();
}
});
});
</script>
Any suggestions or hints? Any help is appreciated.
Fiddle is acting a bit strangely (not working) for me.
You may want to just set a cookie inside of the .change function, that'd probably be the easiest way to do it. When the filter page loads, check to see if the cookie is set, and if it is, run the filter based on the stored cookie value.
Try out: https://github.com/js-cookie/js-cookie
Alternatively, and probably even better, you can use webstorage (localstorage) to accomplish the same thing.
http://www.w3schools.com/html/html5_webstorage.asp

How to bind change event dynamically in jquery

I am doing username availability check. I made jquery ajax call, its working fine and if username already in use i want to make label and textbox in red color. for this purpose i am adding css class in the callback function of $Post() method. The problem I have is css is not applying. I think the problem is in dynamically binding the event So please can any one help me in this. Here is my jquery script,
$(document).on('change', '#uName', function() {
var uName = $(this).val();//get the string typed by user
if (uName!=''){
$.post('<%=request.getContextPath()%>/controller/UserNameCheckController',{'uName':uName},
function(data) {
$('.status').html(data);
var status = $.trim($("#status").text());
if(status=="Username in use try another"){
$('#unameBlock').addClass('error');
}
});
}
else{
$('.status').html('');
}
});
Help me to fix this please. Thanks.
I think the error lies on your class selector
Change
$.trim($("#status").text());
to
$.trim($(".status").text());
//--------^-----------------
try changing it to
var status = $.trim($("#status").html());
it could be .status or #status depends upon the class or id you have used in your html.

Change text color based on background color?

I've a pretty minimalistic site, so I want to add details to it, like a hidden theme switching. But I don't want to tell the user that the theme can be changed, so I want to hide the text.
I've tried this:
var tausta = $(body).css("background-color");
$('.piiloteksti').css("color",tausta);
But it doesn't do anything. What would be the correct approach?
A fiddle.
if($('.piiloteksti').css("color",tausta); is a wrong statement. Thats a syntax error! There shouldn't be any if here.
Either remove if
$('.piiloteksti').css("color",tausta);
or complete the if statement.
if($('.piiloteksti').css("color",tausta)){
// some other code
}
Also $(body) does not refer to anything. Use either $('body') or $(document.body)
I tried to modify CSS, and it works.
// javascript
var tausta = $('body').css("background-color");
if($('.piiloteksti').css("color") == tausta) {
alert(tausta);
}
// css (test)
body{background-color:red;}
.piiloteksti{color:red;}
The syntax of your the if statement was off a little. Also, body must be made a String literal.
var tausta = $("body").css("background-color");
$('.piiloteksti').css("color", tausta);
Example: http://jsfiddle.net/HbAHS/8/
You can hide the element with CSS
.piiloteksti{display:none;} Fiddle
OR if you think that would interfere with your layout then,
.piiloteksti{visibility:hidden;} Fiddle
Or you can just give transparent color to your piiloteksti elements
.piiloteksti{color:transparent;} Fiddle

Categories

Resources