0

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

jcrowson
  • 4,290
  • 12
  • 54
  • 77
  • possible duplicate of [Using JQuery to Access a New Window's DOM](http://stackoverflow.com/questions/7788480/using-jquery-to-access-a-new-windows-dom) – Marc B Nov 29 '11 at 14:57
  • Are you navigating to a completely new page with a full post back? – arb Nov 29 '11 at 14:58
  • Then you'll have to put code in the new page that checks something (like, as suggested, a cookie) and adjusts accordingly. – Pointy Nov 29 '11 at 15:12
  • @LordSnoutimus added an example in my answer - quite simple and straight forward with a cookie .... – Manse Nov 29 '11 at 15:19

1 Answers1

1

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);
        }
    }
}
Manse
  • 37,765
  • 10
  • 83
  • 108
  • Great answer! But since you're already on jQuery I would suggest you give the jQuery Cookie Plugin a run. http://plugins.jquery.com/project/cookie – Filip Nov 29 '11 at 15:37
  • 1
    @Filip thanks .. i have updated the answer to include the plugin as an alternative ... 1.86 KB though !!!!! ;-) – Manse Nov 29 '11 at 15:40
  • I'm making the change on a page before the one with the Wrapper div. How can I set the cookie before even navigating to the page? – jcrowson Nov 29 '11 at 15:40
  • 1
    @LordSnoutimus exactly as it says in my answer .... call setCookie on the page where you want to set the background, then getCookie on the page you want to use the background thats been set - cookies are stored on the client and passed to the server each request – Manse Nov 29 '11 at 15:42