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
Related
Im trying to display a welcome message for a few seconds then have it fade out and not return (unless user deletes cookies). I know i can do this 2 ways using either js cookies or localStorage. This is the code i'm using:
$(document).ready(function() {
if(localStorage.getItem('messageState') != 'shown'){
$("#message").delay(2000).fadeOut();
localStorage.setItem('messageState','shown')
}
$('#message').fadeOut();
});
});
But it's not fading out. Any ideas what i'm doing wrong?
Or would i be better using js cookie?
Here's a fiddle: http://jsfiddle.net/Y2D67/1786/
Delete your last line, the }); and the fadeout works.
$(document).ready(function() {
if(localStorage.getItem('messageState') != 'shown'){
$("#message").delay(2000).fadeOut();
localStorage.setItem('messageState','shown')
}
$('#message').fadeOut();
});
Your syntax is wrong, the closing bracket
})
does not belong
Localstorage would be a fine way to store something like this, I usually go by the rule that localstorage is for data I want to read on the front end and cookies are primarily for reading server-side
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.
I've been trying to search for a way to use cookies to save the change done by toggle on my website, but i can't get my head around cookies. Please help me i'm just new at jQuery and cookies.
<script>
$(document).ready(function(){
$("#switch").click(function(){
$("body").toggleClass("main");
});
});
</script>
You need https://github.com/carhartl/jquery-cookie to manage your cookies. Very simple and effective. You'll just have to modify your script :
$(document).ready(function(){
$("#switch").click(function(){
$("body").toggleClass("main");
$.cookie('your_cookie_name', 'your_cookie_value');
});
});
Good luck.
Load the jQuery cookie plugin, as referenced in Flo's answer. Then you can save the state with:
$(document).ready(function(){
$("#switch").click(function(){
$("body").toggleClass("main");
$.cookie("main", $("body").hasClass("main"));
});
});
You can later get the value of the cookie with:
var main_set = $.cookie("main");
I am pretty new to web design. I just finished my first static website.
What i dont like about it is that the page often reload (each time you change section)
My question is "how to make this kind of nav : http://www.doblin.com/work/#innovation-strategy"
As you see the page doesnt reload when you click on "Set Innovation Strategy / Design, Build + Launch Innovations / Become Better Innovators"
How it s done ?
Is it possible on a static website (html/css/jquery) without sql or so (it may require ajax or ...) ?
Thanks
Taking a look at the code, this page uses some jQuery functions to do this work, check it out:
$(window).hashchange( function(){
var hash = location.hash;
// if a hash has been set
if(hash !== '') {
showContent(hash, origSections);
} else {
// pass in "empty" hash
showContent('', origSections);
}
return false;
});
// call hashchange on initial page load
$(window).hashchange();
// ----------- SHOW CONTENT ----------- //
function showContent(active, all) {
if (jQuery.support.opacity) {
opacity = true;
} else {
opacity = false;
}
This can also be done using CSS3 transitions and animations. Here's a pen based on this Codrops tutorial. I particularly think this is a better approach
But if you want to get dynamic data from somewhere, i advise you to use Ajax(There are some cool jQuery stuff to handle this)
you can use Jquery on your static website. You can go through below link
Jquery
But if you wish to save data and retrieve from server then you need to use Ajax to avoid refreshing page.There are many tutorials available on how to use Ajax
Take a (hard) look at JQuery or Dojo, any of them will be your friend.
Your example uses JQuery.
It can be done on one static page without worries.
Here you have some demos: http://jqueryui.com/tabs/
You can also study jquery on http://w3schools.com/jquery/default.asp
Tried...
<div data-role="page" data-cache="30">
<div data-role="page" data-cache="never">
<div data-role="page" data-cache="false">
<div data-role="page" cache="false">
Nothing seemes to work... so at the moment I'm fixing the problem on the server-side via...
.'?x='.rand()
.'&x='.rand()
I don't want to disable the AJAX just the caching. There has to be a better way though... am I missing something?
Thanks,
Serhiy
Thank you for the answers guys, and even though they didn't quite work for me they did point me in the direction to find the code I was looking for.
This is the code that I found on this gentleman's Github Gist.
https://gist.github.com/921920
jQuery('div').live('pagehide', function(event, ui){
var page = jQuery(event.target);
if(page.attr('data-cache') == 'never'){
page.remove();
};
});
There is also a back button code in that Gist, but I don't seem to need it really as my back button seems to work just fine...
Page caching is now off by default in jQM RC1. See the extract below from the jQM website about page caching: http://jquerymobile.com/demos/1.0rc1/docs/pages/page-cache.html
If you prefer, you can tell jQuery Mobile to keep previously-visited pages in the DOM instead of removing them. This lets you cache pages so that they're available instantly if the user returns to them.
To keep all previously-visited pages in the DOM, set the domCache option on the page plugin to true, like this:
$.mobile.page.prototype.options.domCache = true;
Alternatively, to cache just a particular page, you can add the data-dom-cache="true" attribute to the page's container:
<div data-role="page" id="cacheMe" data-dom-cache="true">
You can also cache a page programmatically like this:
pageContainerElement.page({ domCache: true });
The drawback of DOM caching is that the DOM can get very large, resulting in slowdowns and memory issues on some devices. If you enable DOM caching, take care to manage the DOM yourself and test thoroughly on a range of devices.
Have you tried to overwrite the default value ?
$(document).bind("mobileinit", function(){
$.mobile.page.prototype.options.domCache = false;
});
This works for me
Method 1
This disables AJAX
Read
http://jquerymobile.com/demos/1.0a2/#docs/api/globalconfig.html
Set ajaxLinksEnabled to false and it will not load and cache those pages, just work as normal links.
Method 2
Second idea is to remove cached elements. You can bind to pagehide event and make it remove the page instead. If not present in DOM, the page will be loaded again.
It can be done with this code as a proof of concept:
$('.ui-page').live('pagehide',function(){ $(this).remove(); });
But it needs a little work. The above code breaks the history. It prooves that you will only be able to use it with pages you intend to be leaves in your sitemap tree. Therefore you have to create a special selector for them or bind it to only certain pages.
Also you can bind to a button's click or mousedown event, get its href, generate page id out of it and find the div by id to remove it before jqm tries to look for it.
I have found no advised way of disabling the cache or forcing loading.
Martin's answer should be the right one in my opinion but jQuery Mobile cache the first page no matter what. https://github.com/jquery/jquery-mobile/issues/3249
I've opted to "patch" the behaviour of $.mobile.page.prototype.options.domCache = false and data-dom-cache="true"
$(document).on('pagehide', function (e) {
var page = $(e.target);
if (!$.mobile.page.prototype.options.domCache
&& (!page.attr('data-dom-cache')
|| page.attr('data-dom-cache') == "false")
) {
page.remove();
}
});
Here's my working solution:
$('.selector').live( 'pagebeforecreate', function () {
$.mobile.urlHistory.stack = [];
$.mobile.urlstack = [];
$( '.ui-page' ).not( '.ui-page-active' ).remove();
});
I wrote an (original in German) article about that topic, maybe that helps.
Link to google translated article