How to Change Page Title Using JavaScript

Ciprian on Friday, August 30, 2019 in JavaScript DOM

NEW! Learn JavaScript by example. Code snippets, how-to's and tutorials. Try now!

This JavaScript will modify the text of the browser tab when a visitor focuses or unfocuses the tab. You can display one title when a visitor is focused on the tab, and a different title when they toggle to a different tab or window.

The code below will modify the title of the browser tab on the tab blur event and change it back to the original on the tab focus event.

/**
 * The following code will modify the title of the browser tab on the "blur" event
 * and change it back to the original on the "focus" event.
 */

// Store the original tab title
// Consider storing it in localStorage if you need it across the site
let origTitle = document.title;

// Change title when focusing on tab
function oldTitle() {
    document.title = origTitle;
}

// Function to change title when un-focusing on tab
function newTitle() {
    document.title = 'Please come back!';
}

// Bind functions to blur and focus events
window.onblur = newTitle;
window.onfocus = oldTitle;

Related posts

Leave a Reply

You have to agree to the comment policy.