I try to change the background of a div onclick and preserved it with a cookie. Here is my code. Firstly I can't realize if my cookie has been set and secondly if I can change the background with the value of the cookie.
Can anyone help with an idea?
<div class="container">
<div class="col-md-6">
<div class="one"><a id="1" onClick="addcookie()" href="#">Fisrt Link</a></div>
</div>
<div class="col-md-6">
<div class="two"><a id="2" onClick="addcookie()" href="#">Second Link</a></div>
</div>
</div>
<script src=js/jquery-1.11.1.js></script>
<script src="js/jquery.cookie.js"></script>
<script>
var cookieName = 'cookie1';
function addcookie(){
var date = new Date();
var minutes = 5;
date.setTime(date.getTime() + (minutes * 60 * 1000));
var idi = getDocumentById(this.id);
var cookieValue = "http://path to image/image"+idi+".png";
$.cookie(cookieName, cookieValue, { expires: date });
$('.one').css('background', $.cookie('cookieName'));
}
</script>
<script src=js/bootstrap.js></script>
</body>
Other than what @George already pointed out in a comment (replace
getDocumentById()
- non-existent native function - withdocument.getElementById()
), you'll also have to make sure that you're adding the image URL is coded properly, os instead of......do this...
This is the proper CSS syntax for including background URL's is not...
...but...
...and because if you want to use a variable as a function's parameter, you have to omit the quotes around it, ie.
$.cookie('cookieName')
becomes$.cookie(cookieName)
.Additionally,
this.id
will only return the id of the element if you passthis
as a parameter of your inline function as follows:...then reference the same in your function like this:
...and use it like this:
Here is a jsfiddle where you can try this: http://jsfiddle.net/yxj8w6d0/
EDIT: With a few little modifications (remove the
one
andtwo
classed divs, and addno-repeat
to the background) you have a neat little way of always only adding the background to the element in question, assuming it's what you actually wanted to achieve: http://jsfiddle.net/yxj8w6d0/1/EDIT #2: To get the images loaded if the cookie already exists, create another function that fires on document ready going through your links and checking them against the existing cookies, as follows:
I updated the above fiddle accordingly. Try it by clicking the links first, then running the script again - you'll see that the links will keep their background: http://jsfiddle.net/yxj8w6d0/2/