How to Change Page Title Using JavaScript

on in JavaScript DOM
Last modified on

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