Creating a cookie on click event to change the background

I am working on changing the background of a div onclick and storing it with a cookie. However, I am facing some issues with my code. I can't determine if the cookie has been properly set, and I am unsure about changing the background with the value of the cookie.

Could someone provide some guidance or suggestions on how to resolve this issue?

<div class="container">


<div class="col-md-6">

<div class="one"><a id="1" onClick="addcookie()" href="#">First 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>

Answer №1

Aside from @George's noted correction in a comment (replacing getDocumentById() with document.getElementById()), it is crucial to ensure that the image URL is properly encoded. Instead of...

$('.one').css('background', $.cookie('cookieName'));

...you should do this...

$('.one').css('background', 'url("' + $.cookie(cookieName) + '")');

The correct CSS syntax for background URLs is not...

background:http://path to image/image.png

...but...

background:url("http://path to image/image.png");

Furthermore, when using a variable as a function parameter, the quotes around it must be omitted, like from $.cookie('cookieName') to $.cookie(cookieName).

Additionally, this.id will only return the element's id if you pass this as a parameter in your inline function like this:

onClick="addcookie(this)"

...then reference it in your function like so:

function addcookie(that)

...and use it as follows:

var idi = that.id;

Here is a jsfiddle where you can experiment with this: http://jsfiddle.net/yxj8w6d0/

EDIT: By making slight adjustments (removing the one and two classed divs, and adding no-repeat to the background), you can neatly add the background only to the intended element. Check it out here: http://jsfiddle.net/yxj8w6d0/1/

EDIT #2: To load images if the cookie already exists, create a function that executes on document ready to iterate through your links and compare them with existing cookies, as shown below:

$(document).ready(function() {
    $('.container div a').each(function(){
        if ($.cookie(this.id))
            $(this).css('background', 'url("' + $.cookie(this.id) + '") no-repeat');
    });
});

I have updated the fiddle accordingly. Test it by clicking the links first, then rerun the script - you'll notice the links will retain their background: http://jsfiddle.net/yxj8w6d0/2/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The inability to display a Stylesheet is due to the unsupported MIME type, even though the MIME type seems to be missing when checking for errors

Every time I try to apply a specific style to a particular page on a website (even though the same style functions properly on other parts of the web server), an error message pops up. The error notification states Refused to apply style from 'styl ...

In production, all Next.js API routes consistently return an "Interval Server Error," whereas in development, all routes operate smoothly without any issues

Every time I access any API route in my Next.js application in production, it results in a 500 "Internal Server Error". However, in development mode, all routes function smoothly and provide the expected output. https://i.stack.imgur.com/nPpeV.png https: ...

Struggling with getting my Vue-CLI app deployed on Heroku

After diligently following all the steps outlined in this tutorial: https://codeburst.io/quick-n-clean-way-to-deploy-vue-webpack-apps-on-heroku-b522d3904bc8 I encountered an error message when checking my app at: The error indicated: Method Not Allowed ...

To modify the color of the breadcrumb navigation bar from purple to #d6df23 using PHP

Can someone help me figure out how to change the color of the bar displayed in this link: I need assistance with modifying the breadcrumb navbar. Is there a way to change the color to yellow? I attempted editing the header file, but it didn't produ ...

Inquiry regarding the process of object creation in JavaScript

I recently discovered a method to create your own 'class' as shown below: function Person(name, age){ this.name = name; this.age = age; } Person.prototype.foo = function(){ // do something } Person.prototype.foo2 = function(){ ...

Ways to stop React from refreshing the page upon clicking the submit button

Is it possible to prevent a React component from reloading the page when a submit button is pressed? Here is an example of component code: class MyComponent extends React.Component<IEditCampaignStateProps & IEditCampaignDispatchProps, EditCampaignStat ...

The Electron forge project from publisher-github is failing to detect the environment variable GITHUB-TOKEN

I've set up my .env file with the correct token, but I encountered an error when trying to publish my package on GitHub. An unhandled rejection has occurred inside Forge: Error: Please set GITHUB_TOKEN in your environment to access these features at n ...

Deactivate Mongoose connection in Node.js after completing tasks

Here is a mongoose script I have been using to connect to the local database and perform some operations. However, I am facing an issue with disconnecting the connection after use. const mongoose = require('mongoose'); const db = mongoose.connec ...

Retrieve data from a URL using jQuery's .get method and iterate over each element using

After successfully retrieving the HTML using the jQuery get function and displaying it, I now have a question. How can I use the .each jQuery function to iterate through each div contained within the retrieved data? Specifically, I want to target a single ...

Utilizing loop variables in ng-class and ng-click directive

This piece of code generates a list consisting of seven thumbnails, with the currently active image designated by the active and thumb classes. <div ng-repeat="no in [1, 2, 3, 4, 5, 6, 7]"> <img ng-src="images/{{no}}t.jpg" class="thumb" ng ...

A step-by-step guide on incorporating RAW css into your Jekyll website

I am experiencing an issue with loading a CSS file on my website. <link rel="stylesheet" href="/assets/css/my_file.css"> This file is located at _assets/css/my_file.css. However, when I try to load the page, the CSS file does no ...

"Incorporate React Redux to dynamically load an endless stream of items in batches of x at a time

In order to efficiently display search results using React - Redux, I want to limit the number of displayed results while maintaining optimal performance. Here is my current approach for getting and displaying the results: handleSubmit(event) { event ...

Is there a way to modify the background color of a button once it has been clicked, specifically using JavaScript?

I am looking to change the background color of a button that I have clicked on in my code. Do I need to use loops and conditions for this task? I attempted to access the first index, but I am unsure how to change the background color of other buttons. l ...

What is causing the duplication of leaves when using this DFS implementation?

I created an algorithm to compare if two trees have the same leaves. https://i.sstatic.net/lpO2C.png Both trees display matching leaf numbers in the exact order, resulting in a true outcome. Below is the code that I formulated: function leafSimilar(root ...

Don't forget to retain the checkboxes that were chosen in the

I am looking for a solution to a specific scenario. When I open a modal box and check some checkboxes, I want those same checkboxes to be selected the next time I open it. Below is an example of my code. Main Controller modal function function openModa ...

Creating an array of objects in Node.js can be achieved by simply declaring an array

Here's the structure of my class: var Coin = { _id: null, createGame: function(id) { this._id = id; }, start: function() { } }; My issue is that I am unable to create an array of objects, as I can only create one. Can someo ...

Create a customized navigation menu with both dropdown and dropup options

Is it feasible to create a hover effect that displays both an up and down menu simultaneously? I've tried positioning the up menu absolutely, but it doesn't seem sufficient to me. I want a dual menu setup where the up and down menus display next ...

Instructions for obtaining and assigning a reference to a recently cached associated object within the Apollo client InMemoryCache

My data consists of a set of interconnected items like this: book { id ... related_entity { id ... } } Once Apollo caches it, there are two separate cache objects. The related_entity field on book points to an EntityNode object. Everything ...

Following conventional methods often results in oversized containers and monolithic code

I've heard that it's recommended to use classes for containers and functions for components. Containers handle state, while components are simple functions that receive and send props to and from the containers. The issue I'm encountering i ...

Tips for storing unique values in an object using JavaScript

I need assistance with organizing my log data, which includes camera names and system IP addresses. I am trying to create an object where each unique system IP is a key, with an array of corresponding camera names as the value. Here is the code snippet I h ...