Use JavaScript to change background image of a div in another page - javascript

I'm using the following line to change background of the div Wrapper to an image:
$("#wrapper").css("background","url(images/bg.jpg) no-repeat 0 0");
However, Wrapper exists in another page from the function where I am calling this line of code , so when I navigate to the page with Wrapper in it, it has not changed.
Is there anyway I am able to change the background of Wrapper from another page?
Thanks

You could store the values in a cookie, working example here -> http://jsfiddle.net/manseuk/cEpjc/ :
store it in a cookie on the page you want to set the background :
setCookie('background','url(images/bg.jpg) no-repeat 0 0');
then on the "other" page do this :
$('#div').css('background',getCookie('background'));
For cookie reading and writing you could either use a jQuery plugin (thanks #Filip) or basic JavaScript cookie methods :
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}

Related

How do I store and then retrieve a link to an image in a cookie?

I would like to be able to show a user a picture from one form page to the next. The picture will be dynamic based on what he or she is doing. So, I need to store the path link to that image in a cookie and then load that image on the next page.
How do I do that?
Check the plugin: https://github.com/carhartl/jquery-cookie
and then do:
$.cookie("img", img_url);
[OR]
You can set and get cookie using these functions: (From Quirksmode)
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = escape(name) + "=" + escape(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = escape(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return unescape(c.substring(nameEQ.length, c.length));
}
return null;
}
Use document.cookie to set and get the image URLs.
check this cite for details: w3Schools
It shows that you didn't do much research on this simple thing.
Here's a very simple JSFiddle: fiddle
// Assign the cookie
document.cookie = "imgpath=/your/image.png";
alert(document.cookie);
// Use a regular expression to get the path from the entire cookie string. Sanitizations are left up to you.
var imgPath = /imgpath=([^;]+)/i.exec(document.cookie)[1];
alert(imgPath);
I suggest using the jQuery.cookie plugin mentioned in the other answers though, no need to make it any harder than it already is.
Here is the regular expression explained: http://regex101.com/r/qH6rB5/1 - it shows how the actual value you are interested in, is captured.

How to set Javascript cookie in all the pages / globally?

I'm having a huge problem with my code, I am trying to check if a cookie exists, and if it does exist, i dont want it to do anything.
Its working fine on page1, but when i navigate to page2 it overrides the cookie, instead of doing nothing (the pages is from the same website)
Heres my script
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g,"");
if (x == c_name) {
return unescape(y);
}
}
}
var omgpost = getCookie("omgpost");
if (omgpost == null || omgpost == "") {
setCookie("omgpost", "1", 1);
} else {
alert('cookie installed already');
}
This is working fine, when I don't have the cookie installed and entering this site, I'm adding the cookie, and I'm getting the confirmation message each time I refresh the page1.
But when navigating to page2 its recreating the cookie??? I don't want that! I want the cookie to be there, and can't be changed, only when it has expired, how can I do that?
Set Cookie Path using path=/
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null)
? "" : "; expires="+exdate.toUTCString())
+ "; path=/";
document.cookie=c_name + "=" + c_value;
}

Using javascript to set cookie in IE

document.cookie= "cookiename=cookievalue;
expires=Mon,12Jun2015:00:00:00; path=/;"
I run this script on my Internet Explorer 10 but it doesn't share cookie between 2 IE tab. But when i remove the "expires" properties so it seem to working :
document.cookie= "cookiename=cookievalue ;path=/;"
But i don't want to remove the "expires" properties. So how to resolve this problem ?
2021 update: If you do NOT need to pass information to the server, use localStorage or sessionStorage
I have used this code since mid '90s - it has worked in all browsers on all platforms so far
Include the file and use
setCookie("name","value",expiryDate,"/"); // the last two are optional
// cookie.js file
var cookieToday = new Date();
var expiryDate = new Date(cookieToday.getTime() + (365 * 86400000)); // a year
/* Cookie functions originally by Bill Dortsch */
function setCookie (name,value,expires,path,theDomain,secure) {
value = escape(value);
var theCookie = name + "=" + value +
((expires) ? "; expires=" + expires.toGMTString() : "") +
((path) ? "; path=" + path : "") +
((theDomain) ? "; domain=" + theDomain : "") +
((secure) ? "; secure" : "");
document.cookie = theCookie;
}
function getCookie(Name) {
var search = Name + "="
if (document.cookie.length > 0) { // if there are any cookies
var offset = document.cookie.indexOf(search)
if (offset != -1) { // if cookie exists
offset += search.length
// set index of beginning of value
var end = document.cookie.indexOf(";", offset)
// set index of end of cookie value
if (end == -1) end = document.cookie.length
return unescape(document.cookie.substring(offset, end))
}
}
}
function delCookie(name,path,domain) {
if (getCookie(name)) document.cookie = name + "=" +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
";expires=Thu, 01-Jan-70 00:00:01 GMT";
}
The following sample code will demonstrate setting a cookie of your choosing directly, without requiring input from the user. To store a cookie from your site, simply put a call to the javascript function in your HTML page, like this:
<script type="text/javascript">cookieSet();</script>
The real work is done by the cookieSet() javascript function, which can be either in the area of your HTML page, or in a separate javascript file:
var cookieText = "Put your desired cookie value here";
var cookiePrefix = "";
var myPage = location.href;
var wwwFlag = myPage.indexOf('www');
if (wwwFlag > 0) {
cookiePrefix = "www";
}
var cookieName = cookiePrefix + "cbCookie";
function cookieSet() {
if (document.cookie != document.cookie) {
index = document.cookie.indexOf(cookieName);
} else {
index = -1;
}
if (index == -1) {
document.cookie=cookieName+"="+cookieText+"cbEndCookie; expires=Monday, 04-Apr-2020 05:00:00 GMT";
}
}

How to read/write cookies for local file:/// HTML document?

How can I read/write cookies for local file:/// HTML document using Javascript or jQuery?
I tried this one >>
function setCookie(c_name, value, exdays)
{
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) +
((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function getCookie(c_name)
{
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++)
{
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name)
{
return unescape(y);
}
}
}
But it does not work.
It depends on your browser. Chrome e.g. doesn't allow cookies for local files. see: where cookie saved for local HTML file
This will work locally
// save data value
localStorage.setItem("name", "John");
// retrieve data value
var name = localStorage.getItem("name");
Original answer.
try this one:
https://github.com/carhartl/jquery-cookie
If you need multiple values stored in it try this:
https://github.com/tantau-horia/jquery-SuperCookie
As an alternative to loading the page from file, you can run a webserver and load the page from localhost. Apache comes with OSX and Ubuntu. Once you have set that up you will be able to use cookies on the local page.
Try in different browser mozilla allows local storage cookies

Cookie is not working and returning undefined

I'm using the following code for my set and get Cookie:
$.setCookie = function (c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
};
$.getCookie = function (c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
};
Then I simply created two test click functions for 2 buttons:
$('#quick-true').click(function(){
$.setCookie('quick-status', true, 365);
var get = $.getCookie('quick-status');
alert('Status: '+get);
});
$('#quick-false').click(function(){
$.setCookie('quick-status', false, 365);
var get = $.getCookie('quick-status');
alert('Status: '+get)
});
But when clicking either #quick-true or #quick-false the alert says Status: undefined
Can anyone help me why this is happening. I know quite a bit about Cookies and I worked with them a lot but this time im lost.
Your code looks fine to me, but to be sure I created a test HERE, and it's working as expected for me.
There's probably something other than the code you have posted that is causing the problem, exactly what is hard to tell.

Categories