Vue Js Change Favicon Dynamically : In Vue.js, you can dynamically change the favicon of your web page by manipulating the link element in the head section of the HTML document. The link element is used to define a relationship between the current document and an external resource, such as a favicon. In this tutorial we will learn how to change favicon dynamically in Vue Js using Native Javascript method.
How to Change Favicon Dynamically in Vue Js ?
To change the favicon dynamically, you can follow these steps
- Get a reference to the head element of the page using the
document.head
property in JavaScript. This returns theHTMLHeadElement
object that represents the head section of the HTML document. - Find the link element with the
rel
attribute set to “shortcut icon” using thequerySelector
method. This method returns the first element that matches the specified CSS selector. - Update the
href
attribute of the link element to the URL of the new favicon image using thesetAttribute
method.
With these steps, you can dynamically change the favicon of your Vue.js web page using plain JavaScript.
Vue Js Change Favicon Dynamically Example
<div id="app">
<button @click="changeFavicon('https://s.ytimg.com/yts/img/favicon-vfl8qSV2F.ico')">Youtube Favicon</button>
<button @click="changeFavicon('https://www.google.com/favicon.ico')">Google Favicon</button>
</div>
<script type="module">
const app = new Vue({
el: "#app",
methods: {
changeFavicon(url) {
let favicon = document.querySelector('link[rel="icon"]')
if (!favicon) {
favicon = document.createElement('link')
favicon.setAttribute('rel', 'icon')
favicon.setAttribute('type', 'image/png')
document.head.appendChild(favicon)
}
favicon.setAttribute('href', url)
}
}
})
</script>
A favicon is a small icon that represents a website or webpage. It usually appears next to the webpage title in the browser’s tab, bookmarks, and history. In the given code, there are two buttons labeled as Google and YouTube.
When the user clicks the Google button, it triggers a function that updates the favicon with the Google icon. Similarly, clicking the YouTube button will call a function that replaces the favicon with the YouTube icon.
This functionality is often used by websites to display their unique favicon to users. For example, Google’s favicon is a capital letter G, while YouTube’s favicon is a rectangle with a triangle inside. By changing the favicon, users can easily identify which website they are currently viewing even if they have multiple tabs open in their browser.