Store users choice of CSS-style with local storage (How?) - javascript

The user can choose between 4 different themes (4 different CSS-files) by clicking links. The users choice should be saved (and somehow selected by being bold for example) in local storage and the chosen CSS-style should then be loaded when the user opens up the webpage. The choice should be stored for at least a week.
I am completely new to local storage so I am uncertain of how I should approach this. As far as I understand, localStorage.setItem, localStorage.getItem and onChange() should be included somewhere and somehow.
All code should be in javascript, and no jQuery.
HTML
function changeCSS(sheet) {
document.getElementById('stylesheet_1').setAttribute('href', sheet);
}
var stylesheets = document.getElementsByClassName("left_sub8");
stylesheets[0].addEventListener("click", function(){
changeCSS('inlamning7_utseende1.css');
});
stylesheets[0].addEventListener("click", function(){
changeCSS('inlamning7_utseende2.css');
});
stylesheets[0].addEventListener("click", function(){
changeCSS('inlamning7_utseende3.css');
});
stylesheets[0].addEventListener("click", function(){
changeCSS('inlamning7_utseende4.css');
});
<a class="left_top">Personligt utseende</a><br>
<div class="left_submenu_8" style="display: none;">
<a id="style_1" class="left_sub8" value="inlamning7_utseende1">Default</a><br>
<a id="style_2" class="left_sub8" value="inlamning7_utseende2">Dark</a><br>
<a id="style_3" class="left_sub8" value="inlamning7_utseende3">Pastell</a><br>
<a id="style_4" class="left_sub8" value="inlamning7_utseende4">Gray</a><br>
Any suggestions of how the code would look like to make things work? My main problem is to create code that makes the local storage work, so that´s the top-priority. But have the chosen CSS-file being selected through javascript would be great as well.

You can just save the sheet in your changeCSS():
localStorage.setItem('sheet', sheet);
And then apply it on pageload. So something like
document.addEventListener("DOMContentLoaded", function(event) {
changeCSS(localStorage.getItem('sheet'));
});
Checkout the documentation for the DOMContentLoaded event.

I managed to solve my problem! Thought this might be useful to other than just me so here it is:
Javascript
function changeCSS(sheet) {
document.getElementById('active_stylesheet').setAttribute('href', sheet);
localStorage.setItem('sheet', sheet);
}
var stylesheets = document.getElementsByClassName("left_sub8");
stylesheets[0].addEventListener("click", function(){
changeCSS('inlamning7_utseende1.css');
});
stylesheets[1].addEventListener("click", function(){
changeCSS('inlamning7_utseende2.css');
});
stylesheets[2].addEventListener("click", function(){
changeCSS('inlamning7_utseende3.css');
});
stylesheets[3].addEventListener("click", function(){
changeCSS('inlamning7_utseende4.css');
});
window.onload=function() {
document.getElementById('active_stylesheet').setAttribute("href", localStorage.getItem("sheet"));
};
Note 1: I did not change the html-code so that is the same as in the question above
Note 2: There is another problem now, which is unless the user chooses a theme, no css-document is loaded at all. This is not good, so a css-file needs be loaded by default if no theme is selected by the user. This remains to be solved.

Related

Save dynamic variables on page close

I'm currently building a website for a school project that loads json data into the page dynamically as the user navigates. Here's the code I'm working with right now:
$(function () {
var $divs = $(".divs > div"),
N = $divs.length,
C = 0; // Current
$divs.hide().eq(C).show();
$("#next, #prev").click(function () {
$divs.stop().fadeOut().eq((this.id == 'next' ? ++C : --C) %N).fadeIn();
}); // close click function
}); // close main function
var content = jSONtexts.texts;
$(document).ready(function () {
$("#content0").html(content[0].content);
$("#content1").html(content[1].content);
$("#content2").html(content[2].content);
$("#content3").html(content[3].content);
$("#content4").html(content[4].content);
$("#content5").html(content[5].content);
$("#content6").html(content[6].content);
$("#content7").html(content[7].content);
$("#content8").html(content[8].content);
});
In my html I have divs set up as containers for the particular json data that I want to be presented. It's rudimentary right now, but the user clicks 'next' or 'previous' and a different section of the json loads into the visible div.
What I need is to be able to save what div is showing (maybe using the 'C' variable?) - into a cookie, and load that div when the user returns. I've tried using js.cookie.js, and it's quite possible that I'm using it wrong, Here's what I'm trying:
$( window ).unload(function() {
Cookies.set('pageState', 'C');
}); //close cookie function
But that doesn't seem to be working. It breaks my json loading when I try to put it anywhere in the .js file that would be relevant to the C variable.
I'm stumped. I've looked everywhere on google, and everything that people are saying to try breaks my json function. Help please!
If someone has any ideas I would be eternally grateful!
Thanks
Sam
Cookie is not a best practice to save these data, as cookies will be send with all requests.
Use need to use HTML5 localStorage to save data at client side.
http://www.w3schools.com/html/html5_webstorage.asp
Made demo for the same
document.getElementById("textInput").value = localStorage.getItem("pageState");
window.addEventListener("unload", function() {
localStorage.setItem("pageState", document.getElementById("textInput").value);
});
<input id="textInput" type="text" />
Demo : http://jsfiddle.net/kishoresahas/vvkdge2q/
as #KishoreSahas already suggested in the comments, I would suggest you to use localStorage instead of cookies.
You could store what you need like this
localStorage.setItem("veryimportantdata", "INeedThisLater");
and get it back later like this
var data = localStorage.getItem("veryimportantdata");
console.log(data); // prints out "INeedThisLater"

I want to keep a class changed by jquery across the pages

I'm not sure if this can be done. I'm new on jQuery :)
I have found a way to change a background by clicking an image. But when I refresh the page or change to another page, the background is changed to the original.
Do you know if there is a way to keep the new background selected?
Here is my code:
<script>
$(document).ready(function(){
$("#mood-clasico").click(function(){
$("#chef, #ranchos, #contacto").removeClass("parallax-4, parallax-2");
$("#chef, #ranchos, #contacto").addClass("parallax-1");
});
});
$(document).ready(function(){
$("#mood-chef").click(function(){
$("#chef, #ranchos, #contacto").removeClass("parallax-1, parallax-2");
$("#chef, #ranchos, #contacto").addClass("parallax-4");
});
});
$(document).ready(function(){
$("#mood-kids").click(function(){
$("#chef, #ranchos, #contacto").removeClass("parallax-1, parallax-4");
$("#chef, #ranchos, #contacto").addClass("parallax-2");
});
});
</script>
If you want the state to survive after the window's been closed or page has been navigated away from (to a different domain), use localStorage; otherwise, use sessionStorage (still survives refresh and navigation within the domain). Either way, you'll want to store the css class in a persistent variable and use that to instead of the string, which can help dry the code up a bit too.
Session storage is a little simpler, but your users would probably love you more for using localStorage -- implementation would be something like:
$(document).ready(function() {
var userPref = localStorage.getItem("bg-class") || 'your-default';
$("#chef, #ranchos, #contacto").addClass(userPref);
$("#mood-clasico").click(function(){
swapPref("parallax-4", "parallax-2", "parallax-1");
});
$("#mood-chef").click(function(){
swapPref("parallax-1", "parallax-2", "parallax-4");
});
$("#mood-kids").click(function(){
swapPref("parallax-4", "parallax-2", "parallax-1");
});
function swapPref(out1, out2, inn) {
$("#chef, #ranchos, #contacto")
.removeClass(userPref)
.removeClass(out1)
.removeClass(out2)
.addClass(inn);
localStorage.setItem("bg-class", inn);
}
});
For more persistence (like across different browsers or devices) you'd want to look into the file system api or storing the settings in a database, but based on your question it doesn't seem those options aren't worth the drawbacks. I left out some error handling and things you'd probably want to include, but I'd definitely recommend checking out using the web storage api by mozilla, which actually includes a similar example.
Use the jquery cookie plugin to do this,
details here https://github.com/carhartl/jquery-cookie
then set cookie,
$.cookie("changedBackground", 'true');
and after page refresh this check must be done
if($.cookie("changedBackground")=='true'){
//keep your changed background
}
only with jQuery it's impossible, you have to store the value
try to use session , cockies , external file or data base

jquery load image to div after clicking href

I know this has been asked many times here, actually I found plenty of questions, each of them with a very good answer, I also followed those answers, used the different ways I found but I still don't get it to work.
What I'm trying to do is to load an image into a div, after clicking a link, instead of redirecting to a new page.
I'm using Pure Css (http://purecss.io/) to create a menu, the menu is made of a list, and each list item has a link inside it, like so:
<div class="pure-menu pure-menu-open" id="vertical-menu">
<a class="pure-menu-heading">Models</a>
<ul id="std-menu-items">
<li class="pure-menu-heading cat">Menu heading</li>
<li>Model 1</li>
</ul>
</div>
In that same html file, I have another div where I want to load the image:
<div id="model-map"></div>
I've tried the following ways, using jquery, in a separate js file:
I followed the selected answer for this question, which seemed to have the best approach (Can I get the image and load via ajax into div)
$(document).ready(function(){
console.log("ready"); //this shows on console
$('.model-selection').click(function () {
console.log("clicked"); //this doesn't show after clicking
var url = $(this).attr('href'),
image = new Image();
image.src = url;
image.onload = function () {
$('#model-map').empty().append(image);
};
image.onerror = function () {
$('#model-map').empty().html('That image is not available.');
}
$('#model-map').empty().html('Loading...');
return false;
});
});
As you see, the console.log("clicked") never executes, I'll be ashamed if it's something stupid, cause it seems that the function is not handling the click event properly.
I get the image of course, but in a new page (default behavior of clicking the href) and I want it to load on the div without being redirected. I hope you can help me.
Thanks in advance!
Edit
The code above is working, and both answers are correct, the issue was due to some code inside tags in my html ( YUI code to create the dropdowns for the menu) and it was conflicting with my js file. I moved it to the actual js file and now it works as expected.
Thanks!
You need to use event.stopPropagation();
$('.model-selection').click(function( event ) {
event.stopPropagation();
// add your code here
});
You just need to prevent the default behavior of moving to a new page for <a> tags, to do this say e.preventDefault() first:
...
$('.model-selection').click(function (e) {
e.preventDefault(); // Stops the redirect
console.log("clicked"); // Now this works
...
)};
...

zClip don't work - multiple copy to clipboard JS

I try to make a copy to clipboard button but I don't know why I can't make it.
I load my page with ajax so I call a function to add the zclip to my button when I mouseOver the button. But when I click on it, nothing is happening.
Here are my codes:
JS :
<script type="text/javascript" src="<?php echo JS_DIR?>zclip.min.js"></script>
<script type="text/javascript">
function mouseOver(){
$('.copyMails').each(function (k,n) {
console.log("test");
var copyMails = $(this);
$(this).zclip({
path: '<?php echo JS_DIR?>ZeroClipboard.swf',
copy: function () {
var val = $(copyMails).attr('data-clipboard-text');
return val;
},
afterCopy: function () { console.log($(copyMails).data('clipboard-text') + " was copied to clipboard"); }
});
});
}
</script>
And my button:
<button onmouseover="mouseOver()" data-clipboard-text="<?php echo implode(',', $emails); ?>" class="copyMails" title="Copier les adresses emails">
Copier les adresses emails
</button>
Thanks in advance.
I could not get this to work on my server, I downloaded the ZeroClipboard.swf from zclips website and would not work. I noticed that the swf on zclips website in not the one that they use for their examples. So I created a hyperlink to http://www.steamdev.com/zclip/js/ZeroClipboard.swf and clicked "save link as" compared the size to the one I had downloaded originally and it was bigger. So I put the new one from the link above onto my server and it worked perfectly.
I think if you downloaded the swf from zclips website directly from their download link, this is your problem as it was mine. Try saving my link as a file and then uploading it to your server.
There is an error in your example, at least with what's provided. Trying it in a fiddle prouces your mouseOver function being undefined.
I assume your intent is to copy the data to the clipboard when they click the button, and setup the clipboard when the mouseover event is triggered, correct? If that's the case, your best bet would be to create a single event for this, delegating it to your class of button(s). This way, it's not continuing to configure the clipboard plugin, every time an element is hovered over, for all elements matching your selector.
Here's an example of the code, but I don't believe you can include the SWF path as an external resource within the fiddle so it's not fully functional. So I have put together a version of the code I feel is close. Please give it a try.
JSFiddle: http://jsfiddle.net/adx93ave/3/
$(function () {
$(document).on("mouseover", ".copyMails", function (evt) {
var $btn = $(this);
$btn.zclip({
path: 'http://www.steamdev.com/zclip/js/ZeroClipboard.swf',
copy: $btn.data("clipboard-text"),
afterCopy: function () {
console.log($btn.data('clipboard-text') + " was copied to clipboard");
}
});
});
});

How do I run a jQuery function when any link (a) on my site is clicked

I have a new site build on corecommerce system which does not have much access to HTML and non to PHP. Only thing I can use is JavaScript. Their system is currently not great on page load speed so I wanted at least customers to know something is happening while they wait 5-8 seconds for a page to load. So I found some pieces of code and put them together to show an overlay loading GIF while page is loading. Currently it will run if you click anywhere on the page but I want it to run only when a link (a href) on the site is clicked (any link).
I know you can do a code that will run while page loading but this isn't good enough as it will execute too late (after few seconds)
Anyway, this is my website www.cosmeticsbynature.com and this is the code I use. Any help will be great.
<div id="loading"><img src="doen'tallowmetopostanimage" border=0></div>
<script type="text/javascript">
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
jQuery(document).click(function()
{
if(ns4){ld.visibility="show";}
else if (ns6||ie4)
var pb = document.getElementById("loading");
pb.innerHTML = '<img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0>';
ld.display="block";
});
</script>
Doing this will be easier if you include jQuery in your pages. Once that is done, you can do:
$('a').click(function() {
// .. your code here ..
return true; // return true so that the browser will navigate to the clicked a's href
}
//to select all links on a page in jQuery
jQuery('a')
//and then to bind an event to all links present when this code runs (`.on()` is the same as `.bind()` here)
jQuery('a').on('click', function () {
//my click code here
});
//and to bind to all links even if you add them after the DOM initially loads (`on()` is the same as `.delegate()` here; with slightly different syntax, the event and selector are switched)
jQuery(document).on('click', 'a', function () {
//my click code here
});
Note: .on() is new in jQuery 1.7.
what you are doing is binding the click handler to the document so where ever the user will click the code will be executed, change this piece of code
jQuery(document).click(function()
to
jQuery("a").click(function()
$("a").click(function(){
//show the busy image
});
How about this - I assume #loading { display:none}
<div id="loading"><img src="http://www.cosmeticsbynature.com/00222-1/design/image/loading.gif" border=0></div>
<script type="text/javascript">
document.getElementById('loading').style.display='block'; // show the loading immediately
window.onload=function()
document.getElementById('loading').style.display='none'; // hide the loading when done
}
</script>
http://jsfiddle.net/vol7ron/wp7yU/
A problem that I see in most of the answers given is that people assume click events only come from <a> (anchor) tags. In my practice, I often add click events to span and li tags. The answers given do not take those into consideration.
The solution below sniffs for elements that contain both events, which are created with jQuery.click(function(){}) or <htmlelement onclick="" />.
$(document).ready(function(){
// create jQuery event (for test)
$('#jqueryevent').click(function(){alert('jqueryevent');});
// loop through all body elements
$('body *').each(function(){
// check for HTML created onclick
if(this.onclick && this.onclick.toString() != ''){
console.log($(this).text(), this.onclick.toString());
}
// jQuery set click events
if($(this).data('events')){
for (key in($(this).data('events')))
if (key == 'click')
console.log( $(this).text()
, $(this).data('events')[key][0].handler.toString());
}
});
});
Using the above, you might want to create an array and push elements found into the array (every place you see console.log

Categories

Resources