If you’ve ever used some sort of messaging app in your browser, you’ve probably noticed how the browser tab icon(favicon) will suddenly change when you get a message to notify you even if you are in another tab. This kind of effect is helpful to users and also can boost engagement rates for your application, a win-win. The best part is that adding a cool effect like this only takes a few lines of code!
Video Tutorial and Example
If you prefer a video tutorial to reading, you can watch this, otherwise the written tutorial continues below.
The only thing you’ll need for this tutorial are:
- A basic web development environment
- 2 images that you want to switch between for your standard and dynamic favicon
If you don’t have any images selected, you can use these images as placeholders:
Setting Default Favicon
The first thing you need to do is go to your index page and set the image you want as your site icon by default. The way to do this is by creating a link element in your index.html header element and setting the rel value to ‘icon’ and the href tag to URL path for your image file, it should look something like this:
<link id="favicon" rel="icon" href="/path/to/image.png"/
Implementing HTML and Counter Logic with JSX
- To handle state in our React app we are using hooks, creating a state object called
countwith a default value of 0 that can be updated using
- Next we have our increment function which takes the current state and adds 1
- This function is the same as increment but subtracts from our count value
- The basic structure for the app, a container div containing a header, an H2 tag which will be modified dynamically to show our current count, and 2 buttons to increment and decrement our count
Update Favicon based on current count value
Now with the basic setup out of the way we can finally modify our favicon using that counter value. To do that we will create a
useEffect hook to check our count value and modify the favicon depending on the condition we set.
The code above can be easily modified to fit your use case by simply changing the state value being monitored from
count to whatever value you want. Some example ideas:
- New message added to state array
- Game over state update
- Error notices
A more advanced use case could be simulating an animated favicon by constantly cycling through an array of images. To be more efficient you can also use the Canvas API to customize your default favicon and then convert it back to an image. This could be used to continually increase the count on the favicon for something like a chat app so the user can see from the favicon how many messages they have waiting for them.
You now have a working dynamic favicon and some inspiration for more advanced use cases to improve the user experience for your app. Let me know if you struggled anywhere with the code or have additional questions