How to Display Image Based on Cookies in HTML
- Understanding Cookies and Their Importance
- Setting Up Your HTML Structure
- Setting Cookies with JavaScript
- Reading Cookies to Display the Image
- Conclusion
- FAQ

When it comes to enhancing user experience on your website, displaying images based on cookies can be a game-changer. Cookies allow you to store small pieces of data on a user’s device, enabling you to customize their experience.
In this article, we will explore how to effectively display images based on cookie values using HTML and JavaScript. Whether you want to show personalized content or simply enhance your site’s interactivity, understanding how to manipulate cookies is essential. By the end of this guide, you’ll have the knowledge to implement cookie-based image displays seamlessly.
Understanding Cookies and Their Importance
Cookies are small text files stored on a user’s device that contain data specific to a website. They can track user sessions, preferences, and other essential information. When you utilize cookies to display images, you can create a more personalized experience for users. For example, if a user visits your site and selects their favorite theme, you can save that preference in a cookie. On subsequent visits, you can read that cookie and display the corresponding image or theme.
To get started with displaying images based on cookies, we will use HTML and JavaScript. While this method doesn’t involve Git commands, it’s essential to understand how to manage your project files effectively with Git.
Setting Up Your HTML Structure
First, let’s create a simple HTML structure where we will display the image. This structure will include a basic layout with an image tag and a button to set the cookie.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Display Image Based on Cookies</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>Personalized Image Display</h1>
<img id="displayImage" src="" alt="Image based on cookie" />
<button onclick="setCookie('image', 'image1.jpg', 7)">Set Image 1</button>
<button onclick="setCookie('image', 'image2.jpg', 7)">Set Image 2</button>
</body>
</html>
In this HTML file, we have an image element with the ID “displayImage” and two buttons that set different cookies for the images.
Output:
HTML structure ready with buttons to set cookie images.
Setting Cookies with JavaScript
Next, we need to create a JavaScript function that sets the cookie when a button is clicked. This will allow us to store the user’s image preference.
function setCookie(name, value, days) {
const expires = new Date(Date.now() + days * 864e5).toUTCString();
document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=/';
}
This function takes three parameters: the name of the cookie, its value, and the number of days until it expires. It constructs a cookie string and saves it in the user’s browser.
Output:
Cookie set successfully.
Reading Cookies to Display the Image
Now that we can set cookies, we need a way to read them and display the corresponding image. This is where another JavaScript function comes into play.
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return decodeURIComponent(parts.pop().split(';').shift());
}
window.onload = function() {
const imageName = getCookie('image');
if (imageName) {
document.getElementById('displayImage').src = imageName;
}
};
In this code, the getCookie
function retrieves the value of the specified cookie. When the window loads, we check if the cookie exists and set the image source accordingly.
Output:
Image displayed based on cookie value.
Conclusion
Displaying images based on cookies in HTML is a straightforward yet effective way to enhance user experience on your website. By leveraging cookies, you can tailor the content to match user preferences, making your site more engaging and personalized. With the HTML structure and JavaScript functions provided in this article, you can easily implement this feature. As you continue to explore web development, remember that cookies are a powerful tool for creating dynamic and interactive web applications.
FAQ
-
What are cookies in web development?
Cookies are small text files stored on a user’s device that contain data specific to a website. -
How can I set a cookie in JavaScript?
You can set a cookie in JavaScript using thedocument.cookie
property, specifying the name, value, expiration date, and path. -
Can I store multiple cookies?
Yes, you can store multiple cookies by using different names for each cookie. -
How do I delete a cookie?
To delete a cookie, set its expiration date to a time in the past. -
What is the maximum size of a cookie?
The maximum size of a cookie is typically around 4KB.
Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.
LinkedIn