Elevate Your Website's Look: Dynamic Favicon with JavaScript
"Revamp Your Website with Dynamic Favicon in JavaScript"
Problem: ๐๐งพ
A client requested that the favicon be changed depending on whether the user opened the tap
To set a specific icon
Or open a different tap
Another icon appears
In the end, the icon will look like this
*When the user is in the tap
*
*When the user is in the different tap
*
Unlock the potential of your website's visual appeal by adding a dynamic touch to its favicon. In this tutorial, you'll discover how to seamlessly change your site's favicon based on the time of day using JavaScript. Elevate your web development skills and give your users a personalized and engaging experience.
It's all about
is Document: visibilitychange event
Article:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Ret</title>
<script type="module" src="/src/main.jsx"></script>
</head>
<body>
<div id="root"></div>
<script>
// Get the current hour
var currentHour = new Date().getHours();
// Define the day and night icons
var dayIcon = "/day-icon.svg";
var nightIcon = "/night-icon.svg";
// Choose the appropriate icon based on the current hour
var iconPath = currentHour >= 6 && currentHour < 18 ? dayIcon : nightIcon;
// Set the favicon dynamically
var linkElement = document.querySelector("link[rel='icon']");
linkElement.href = iconPath;
</script>
</body>
</html>
The icon changes depending on whether the user has opened the page or not
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/onpage.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>my stite </title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
<script >
var linkElement = document.querySelector("link[rel='icon']");
window.addEventListener('visibilitychange', () => {
linkElement.href = document.hidden ? "start.png":"onpage.svg";
});
</script>
</body>
</html>
Pausing music on transitioning to hidden
document.addEventListener("visibilitychange", () => {
if (document.visibilityState === "visible") {
backgroundMusic.play();
} else {
backgroundMusic.pause();
}
});
for icons https://icons8.com/icons
Upgrade your website's user experience by implementing this simple JavaScript trick. Learn the step-by-step process and make your site more professional and visually appealing. Don't miss out on this opportunity to stand out in the competitive world of web development! ๐โจ #javascript #webdevelopment #favicon #programmingtips
Top comments (0)