Ava Juan
Ava Juan

Reputation: 113

How to change Page title & Play Notification Sound when I switch tab?

When the user is changing the tab. I want to play notification sound and change the title of the page to grab attention.

How can I do it with JavaScript.

This is the code I have used and isn't working.

<script>
  var message = "Come Back...";
  var original = document.title;
  
  window.onblur = function () { document.title = message; }
  window.onfocus = function () { document.title = original; }
 </script>

Upvotes: 2

Views: 623

Answers (1)

Ketan Ramteke
Ketan Ramteke

Reputation: 10655

You can achieve it very easily:

Here is the full example:

<html>
  <head>
    <meta charset="UTF-8" />
    <script src="script.js"></script>
    <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
  </head>
  <body>
    <h1>Focus</h1>
  </body>
  <script>
    setInterval(checkFocus, 100);
    var audio = new Audio(
      "https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3"
    );
    audio.loop = true;
    function checkFocus() {
      if (document.hasFocus()) {
        document.title = "Main Title";
        audio.pause();
      } else {
        document.title = "Title Change";
        audio.play();
      }
    }
  </script>
</html>

Working Demo

Working App Demo Code stackblitz.com

Upvotes: 3

Related Questions