Changing your site's favicon with Javascript

function change_favicon(img) { var favicon = document.querySelector('link[rel="shortcut icon"]'); if (!favicon) { favicon = document.createElement('link'); favicon.setAttribute('rel', 'shortcut icon'); var head = document.querySelector('head'); head.appendChild(favicon); } favicon.setAttribute('type', 'image/png'); favicon.setAttribute('href', img); } change_favicon('https://codepad.co/img/icn_logo.png');
Little function to change your site's favicon problematically to any png.

img variable must be a string, and img must be a png.

If you do not already have a link tag created the function will create one for you and put it in the head section of your site.

7 Responses

Ok, so that should say programatically not problematically.
Thanks for sharing this! It's really wonderful and amazing. :)
Would this work as a basis for changing the icon after the page has loaded. Say for notifications via the favicon for message numbers etc.
@Jake Moss Yep, that's exactly what it's meant to be used for (e.g. like how slack notifications work in the browser). I use it for my site songfari when the track changes I put the album artwork as the favicon.
This works perfect --- just change the link https://codepad.co/img/icn_logo.png on the last statement change_favicon(' https://codepad.co/img/icn_logo.png'); to the url of your favicon image...perfect guys.
This works perfect --- just change the link https://codepad.co/img/icn_logo.png on the last statement change_favicon(' https://codepad.co/img/icn_logo.png'); to the url of your favicon image...perfect guys.
This works perfect --- just change the link https://codepad.co/img/icn_logo.png on the last statement change_favicon(' https://codepad.co/img/icn_logo.png'); to the url of your favicon image...perfect guys.

Write a comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.