Skip to content
Related Articles

Related Articles

How to change favicon dynamically?
  • Last Updated : 17 Feb, 2020

You may probably notice that many social networks and modern web applications have dynamic favicons. Dynamic favicons may be for different purposes, for example, social networks use it to display notifications or messages. Some websites also have the percentage-based favicon that tracks the levels of success, and if you complete a level, the favicon is replaced with a success icon. The favicon is changed to grab people’s attention. You can rotate between different icons for different pages of your web application.

To change favicons dynamically, we will create two javascript functions, to change favicons GeeksforGeeks and Technical Scripter respectively. We will assign a constant variable and get them by the favicon Id with the getElementById() function. After that, we will create 2 functions and assign two buttons for that. By hovering those buttons favicon will change.

Below example illustrates the approach:
Example: To begin with, we will create a HTML page with two buttons on it. These buttons will help to change the favicon using mouse hover.

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>Dynamic Favicon</title>
    
    <!-- Default favicon image -->
    <link id="favicon" rel="icon"
          href="image_name.png"
          type="image/png" 
          sizes="16x16">
    
    <!--To style the Buttons-->
    <style>
        .btn1 {
            background-image: url('img2.png');
            border: none;
              
        }
        .btn2 {
            background-image: url('img.png');
            border: none;
        }
          
        .container {
            text-align: center;
        }
          
        h1 {
            color:green;
        }
    </style>
</head>
  
<body>
    <div class="container">
    <h1>GeeksforGeeks</h1>
    <h3>Change favicon with JavaScript</h3>
    
    <!--Creating buttons to change favicons on 
        the hover of the mouse on the button-->
    <button class="btn1" type="button" onmouseover="toRed()">
      GeeksforGeeks
    </button>
    <button class="btn2" type="button" onmouseover="toBlue()">
      Tecnical Scripter
    </button>
    
    <script>
        
        // Assign a constant variable and get them by the favicon Id
        const favicon = document.getElementById("favicon");
        
        // Creating a function for the button GeeksforGeeks
        function toRed() {
            favicon.setAttribute("href", "img2.png"); 
        }
        // Creating a function for the button Techiniacl Script
        function toBlue() {
            favicon.setAttribute("href", "img.png");
        }
    </script>
    </div>
</body>
  
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up
Recommended Articles
Page :