Javascript on page active

How to Detect if an Element is Active using JavaScript?

To detect if an element is active or not, you can use the activeElement property of the Document interface. The document.activeElement property is a read-only property and it returns the element that is currently in focus.

If there is no focused element, the activeElement property returns null .

Let’s try to understand it with the help of an example.

Suppose, we have two input elements and a textarea in our HTML document to collect the user’s first name, last name and address.

We have assigned a unique id to each field so that we can get the id of that element which is currently active/focused. To show the id of the currently focused element, we have also added a span in our HTML.

 
The active element's id is:

Now, inside our JS file, we have to add an event listener to the document using the addEventListener() method which will listen to the mouseup event.

The addEventListener() method will get fired every time the user focuses on an element using his mouse pointer. It will then call a callback function where we have put the code to get the currently active element’s id.

So, to check if any specific element is currently active or not, you can compare its id with the id returned by the document.activeElement.id property.

// Get the span element let activeId = document.getElementById('activeId'); // Listen to the mouseup event document.addEventListener('mouseup', function(event)< let activeElementId = document.activeElement.id; // get focused element's id activeId.innerText = activeElementId; // update text of the span >);

After running the above code, you will get the following output:

Note: The above solution will only work if the user focuses on an element using his mouse pointer. But, if the user uses the TAB key to focus on the element, it will not work.

In that case, we have to add one more event listener which will fire as soon as the user releases a key. Inside that event listener, we will filter only the TAB key presses.

To check if the key pressed is a TAB key, we can use the event.key property. The event.key property returns the name of the key pressed as a string.

Below is the enhanced version of the above code:

// Get the span element let activeId = document.getElementById('activeId'); // Function to get focused element's Id function getActiveElementId() < let activeElementId = document.activeElement.id; // get focused element's id activeId.innerText = activeElementId; // update text of the span >// Listen to the mouseup event document.addEventListener('mouseup', getActiveElementId); // Listen to the keyup event document.addEventListener('keyup', function(event) < // check if key pressed is a TAB key if(event.key=='Tab')< getActiveElementId(); // call the function >>);

Here is the outcome of the above program:

As you can see from the above output, the updated code is now working on TAB key press as well as with the mouse pointer.

Conclusion

In this article, we learned how we can detect if an element is active or not using JavaScript.

To detect if an element is currently active or not, you can use the document.activeElement property. It returns the element which is currently focused.

Источник

How TO — Add Active Class to Current Element

Learn how to add an active class to the current element with JavaScript.

Highlight the active/current (pressed) button:

Active Element

Step 1) Add HTML:

Example

Step 2) Add CSS:

Example

/* Style the buttons */
.btn border: none;
outline: none;
padding: 10px 16px;
background-color: #f1f1f1;
cursor: pointer;
>

/* Style the active class (and buttons on mouse-over) */
.active, .btn:hover background-color: #666;
color: white;
>

Step 3) Add JavaScript:

Example

// Get the container element
var btnContainer = document.getElementById(«myDIV»);

// Get all buttons with inside the container
var btns = btnContainer.getElementsByClassName(«btn»);

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) btns[i].addEventListener("click", function() var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(» active», «»);
this.className += » active»;
>);
>

If you do not have an active class set on the button element to start with, use the following code:

Example

// Get the container element
var btnContainer = document.getElementById(«myDIV»);

// Get all buttons with inside the container
var btns = btnContainer.getElementsByClassName(«btn»);

// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) btns[i].addEventListener("click", function() var current = document.getElementsByClassName("active");

// If there’s no active class
if (current.length > 0) <
current[0].className = current[0].className.replace(» active», «»);
>

// Add the active class to the current/clicked button
this.className += » active»;
>);
>

Источник

How to Detect Browser Window is Active or not – JavaScript

Sometimes you may want to take more control over your user Browser when he/she opens your website in a Browser Window.

For example – you want to know when the user closes the Browser Tab and execute your code.

If you want to know how much time the user active on your website, in this case, you can use JavaScript. Using that you only enabled the timer when the user is an active tab on your website.

Or you want to run the Animation only when the user is active otherwise stop it.

This kind of functionality you have seen on websites or PTC sites that provide ads viewing to the users. They only count the ads view when the user is active on their website until a given time otherwise they cancel the view after the specific time.

In this tutorial, I show how you can use JavaScript to detect whether Browser Tab Window is active or not.

How to Detect Browser Window is Active or not - JavaScript

Contents

1. Example

For finding the Browser Tab is currently active or not I defined two events on window –

  • focus – for detecting active state, when this event trigger I start the timer
  • blur – for detecting inactive, state. From where I stop the timer by clearing the Interval.

On focus event, define the code that you want to execute when it is active and within blur event define which you want to do when it is inactive.

Completed Code

  var count = 0; var myInterval; // Active window.addEventListener('focus', startTimer); // Inactive window.addEventListener('blur', stopTimer); function timerHandler() < count++; document.getElementById("seconds").innerHTML = count; >// Start timer function startTimer() < console.log('focus'); myInterval = window.setInterval(timerHandler, 1000); >// Stop timer function stopTimer()

2. Conclusion

Within the example, I use it to count the number of seconds the user active on the website. You can also pause the playing video or stop some of the scripts when it is not using the website.

If you found this tutorial helpful then don’t forget to share.

Источник

JavaScript: Detect user activity / inactivity.

This is a short guide on how to detect user activity or inactivity using JavaScript. To do this, we will capture user events such as mouse movements, touch screen presses and keyboard presses.

Logging inactive users out or displaying popups / adverts.

There are a number of reasons why you might want to do this. The three reasons that immediately spring to mind are:

  1. You want JavaScript to log the user out after they’ve been inactive for too long. That or you want to warn them that they are about to be logged out.
  2. You want to pause a polling Ajax request.
  3. There is an advert or a popup that you want to display if the user has been idle for a set period of time.

JavaScript function that detects activity / inactivity.

In the code below, I will be using plain JavaScript as not everyone wants to have to include the entire JQuery library for a small piece of functionality.

Take a look at the following function, which I have heavily commented:

function activityWatcher() < //The number of seconds that have passed //since the user was active. var secondsSinceLastActivity = 0; //Five minutes. 60 x 5 = 300 seconds. var maxInactivity = (60 * 5); //Setup the setInterval method to run //every second. 1000 milliseconds = 1 second. setInterval(function()< secondsSinceLastActivity++; console.log(secondsSinceLastActivity + ' seconds since the user was last active'); //if the user has been inactive or idle for longer //then the seconds specified in maxInactivity if(secondsSinceLastActivity >maxInactivity) < console.log('User has been inactive for more than ' + maxInactivity + ' seconds'); //Redirect them to your logout.php page. location.href = 'logout.php'; >>, 1000); //The function that will be called whenever a user is active function activity() < //reset the secondsSinceLastActivity variable //back to 0 secondsSinceLastActivity = 0; >//An array of DOM events that should be interpreted as //user activity. var activityEvents = [ 'mousedown', 'mousemove', 'keydown', 'scroll', 'touchstart' ]; //add these events to the document. //register the activity function as the listener parameter. activityEvents.forEach(function(eventName) < document.addEventListener(eventName, activity, true); >); > activityWatcher();

Code drilldown.

  1. Created a JavaScript variable called secondsSinceLastActivity. This variable contains the number of seconds that have passed since the user was last active.
  2. Using the maxInactivity variable, we set the maximum number of seconds that should pass before we consider the user to be inactive. In the case above, I have set this to 300 seconds, which is 5 minutes. You can obviously change this to suit your own needs.
  3. After that, we used the setInterval method to create a counter that runs every second. This counter increments the secondsSinceLastActivity variable and checks to see if the user has been inactive for too long. In the example above, I redirect the user to a page called logout.php. However, you can replace this piece of code to redirect to a different URL or display a popup, etc.
  4. We then created a function called activity. This function is called whenever a user carries out an action on the page. In this case, the function simply resets the secondsSinceLastActivity variable back to 0.
  5. We created an array containing the names of DOM events that we want to consider as activity. In the code above, we are using: mousedown, mousemove, keydown, scroll and touchstart. These are explained further down.
  6. Finally, we looped through the array and added an event listener to the document using the addEventListener() method.

If you run the JavaScript function above, you should see something like this in your browser’s console:

inactivity javascript

The counter in the screenshot above was reset the first time after I moved my mouse. It reset the second time when I pressed a key on my keyboard.

Activity events.

The code above uses five different types of events to determine user idleness. These are:

  • mousedown: Occurs when a key on the mouse is pressed.
  • mousemove: Fires when the mouse is moved.
  • keydown: This event fires whenever a key on the keyboard is pressed.
  • scroll: Occurs when the document is scrolled.
  • touchstart: Fires when the user touches a touch screen (mobile device, etc).

Note that these event handlers are applied to the document object, which represents the entire HTML document that has been loaded into the browser.

Источник

How to Detect If the Browser Tab Is Active or Not Using JavaScript?

Browser tab being active can mean two different things:

  1. Has the user switched to another tab/window?
  2. Has the window lost focus? For example, by clicking on the browser frame (such as in the address bar, the web console, etc.), or when a browser dialog shows (such as print, find, alert, confirm, etc.), etc.

If you’re looking for the first, then you should consider using the Page Visibility API. For the second, you should consider using window focus and blur events.

Using the Page Visibility API

Using the Page Visibility API, you can listen for the visibilitychange event on the document object to see if the document is visible or hidden (i.e. whether the user switched to another tab or window). For example:

document.addEventListener('visibilitychange', function (event) < if (document.hidden) < console.log('not visible'); >else < console.log('is visible'); >>);

Although, this has good browser support, you may have to use vendor prefixes for the event name and the document.hidden property as shown in the example on MDN.

Using window focus and blur Events

You can use the focus and blur events on the window object to check if the window is still active like so:

window.addEventListener('focus', function (event) < console.log('has focus'); >); window.addEventListener('blur', function (event) < console.log('lost focus'); >);

Please be aware of the fact that the window blur event is not only triggered when the user switches the browser tab, but anytime the window loses focus. For example when clicking on the browser frame (such as in the address bar, the web console, etc.), when a browser dialog shows (such as print, alert, confirm, find, etc.), etc. If this is not the behavior you’re looking for then perhaps you should consider using the Page Visibility API instead.

Hope you found this post useful. It was published 01 Jan, 2021 . Please show your love and support by sharing this post.

Источник

Читайте также:  Работа date в java
Оцените статью