Set cookie and replace image based on URL

Hi,

I am wanting to set a cookie based on a dynamic URL, e.g http://www.website.com/?ref=cookieval

I then want to replace an image on the page with an image using the
name of the cookie, e.g <img src="/images/cookieval.png" />

How would I do this? I think I can use

$(".banner").html("<img src="/images/cookieval.png");

But I don’t know how to set the cookie from the URL and then use it in the jQuery .html() part.

Any ideas how I would do this?

Thanks!

Hi,

Why the need for cookies?
Why not just read the value from the query string and set the url of the image based on that?

i.e.

var src = getQueryStringVal("ref") + ".png";
var img = document.getElementById("myImg");
img.src = src;

Thanks, That would work on one page, but the other pages do not use the dynamic URL, they carry a cookie through.

So let me see if I got you right:

You have a page, (e.g. index.html).
When somebody arrives at that page and the query string ?ref=cookieval is present in the url, you want to set a cookie (e.g. imageSrc = cookieval).
Then, on that page and every subsequent page the user visits, you want to read the cookie value and replace an already existing image on the page, with one whose name is stored in the cookie (e.g. img src="myImage.png" should become img src="cookieval.png").

Did I get that right?

You can use jQuery Cookie plugin for setting and reading cookie values

Hasn’t that been discontinued in favor of JSCookie?

Sure. But it’s jQuery version also works well.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.