This article was originally posted on dev.to.No intro just get to the code
Let’s Get Started
First things first, we are going to need a project base. For this, I am going to use create-react-app. However, the code can be used in any JavaScript project. We’ll just need access to thedocument
object.
The code for this project is available on Github
Step 1: Initialise
Step 2: Find file
Open yourApp.js
file.
Step 3: Magic
Create a function above theApp
function called getBrowserHiddenProps
. This function will get the correct properties for us to use based on the browser we are on.
hidden
and visibilityChange
values using a shorthand method. By not defining the keys of the object, the keys will default to the variable name. Below would achieve the same effect as above.
App
function.
hidden
and visibilityChange
as an object. This was so we can deconstruct the return value of the getBrowserHiddenProps
function. We’re also checking to make sure that we are able to add an event listener to the document object and to ensure the hidden
value is not undefined
.
Next, we need to add the event listener based on the visibility event (visibilityChange
).
hidden
value and act of it. In our case, we’ll be asking the user to come back because we miss their attention.
Step 4: Possiblities
Now, changing the tab title may not be that useful, however, there are a few things that you could do when a user moves to another tab. One of the most useful reasons to do this would be to send a Google Analytics Event. This will allow you to start seeing when users are leaving your page and if they return. Very cool. A lot of this code was leverage from the Page Visibility API page on MDN. I’d recommend checking out the page to learn more about this if you are interested.Thank you for reading my article, it really means a lot! ❤️ Please provide any feedback or comments, I’m always looking to improve and having meaningful discussions.