Concealing the cursor inactivity through JavaScript

Is there a way to utilize JavaScript to change the cursor attribute to none after a period of mouse inactivity, like five seconds, and then revert it back to auto once the mouse becomes active again?

EDIT: I am aware that none is not an official value for the cursor property. However, many web browsers seem to support it. Also, I am the primary user so confusion is unlikely to occur.

I have attempted two scripts that provide similar functionalities:

window.addEventListener("mousemove",
    function(){
        document.querySelector("#editor").style.background = "#000";
        setTimeout("document.querySelector('#editor').style.background = '#fff'", 5000);
    }
, true);

and

var timeout;
var isHidden = false;

document.addEventListener("mousemove", magicMouse);

function magicMouse() {
    if (timeout) {
        clearTimeout(timeout);
    }
    timeout = setTimeout(function() {
        if (!isHidden) {
            document.querySelector("body").style.cursor = "none";
            document.querySelector("#editor").style.background = "#fff";
            isHidden = true;
        }
    }, 5000);
    if (isHidden) {
        document.querySelector("body").style.cursor = "auto";
        document.querySelector("#editor").style.background = "#000";
        isHidden = false;
    }
};

Both of these scripts change the background color to white when the mouse remains inactive for more than five seconds, and back to black when the cursor is moved. However, they do not successfully hide the cursor as intended. Interestingly, executing

document.querySelector("body").style.cursor = "none";
directly in the JavaScript console functions correctly. Unfortunately, when integrated into the scripts, it does not work.

I am sharing these scripts to demonstrate my current progress in attempting to achieve this functionality. I am not specifically requesting fixes for these scripts; rather, if you know of a more effective method to hide the cursor, please do share.

Answer №1

When it comes to CSS 2, the value none is not considered valid for the cursor property. However, in CSS 3, this value is actually acceptable.

Alternatively, you could potentially utilize a custom cursor that is transparent when loaded from a URI.

Nevertheless, I would caution against implementing this as it may prove to be quite distracting for the user experience.

Answer №2

In my experience, this solution has proven effective in Firefox 3.6.13 as long as the cursor is positioned over a genuine element without a custom cursor (it won't work if hovering over a form field or link, for instance). However, I must advise against using this method due to its non-standard nature and negative impact on usability.

As a side note, it's better to avoid using querySelector() whenever possible and opt for alternatives like document.body or document.getElementById().

(function() {
    var mouseTimer = null;
    var cursorVisible = true;

    function hideCursor() {
        mouseTimer = null;
        document.body.style.cursor = "none";
        cursorVisible = false;
    }

    document.onmousemove = function() {
        if (mouseTimer) {
            window.clearTimeout(mouseTimer);
        }
        if (!cursorVisible) {
            document.body.style.cursor = "default";
            cursorVisible = true;
        }
        mouseTimer = window.setTimeout(hideCursor, 5000);
    };
})();

Answer №3

I found this solution to be effective (originally sourced from https://gist.github.com/josephwegner/1228975).

It is important to note the mention of an html element identified by the id "wrapper".

//Utilizes jQuery - http://code.jquery.com/jquery-1.6.4.min.js
$(document).ready(function() { 


    var idleMouseTimer;
    var forceMouseHide = false;

    $("body").css('cursor', 'none');

    $("#wrapper").mousemove(function(ev) {
            if(!forceMouseHide) {
                    $("body").css('cursor', '');

                    clearTimeout(idleMouseTimer);

                    idleMouseTimer = setTimeout(function() {
                            $("body").css('cursor', 'none');

                            forceMouseHide = true;
                            setTimeout(function() {
                                    forceMouseHide = false;
                            }, 200);
                    }, 1000);
            }
    });
});

Answer №4

If you are still searching for a solution in 2019, like I was, this method is effective on FF 71 and Chrome 78:

var EXAMPLE = {
  INIT: {
    MOUSE_IDLE: 3000
  },
  hideCursor: function() {
    $("#game").css('cursor', 'none');
    $("#game").on("mousemove", EXAMPLE.waitThenHideMouse);
  },
  waitThenhideCursor: function() {
    $("#game").css('cursor', 'default');
    $("#game").off("mousemove", EXAMPLE.waitThenHideMouse);
    setTimeout(EXAMPLE.hideMouse, EXAMPLE.INIT.MOUSE_IDLE);
  },
  showCursor: function() {
    $("#game").off("mousemove", EXAMPLE.waitThenHideMouse);
    $("#game").css('cursor', 'default');
  },
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

This code is straightforward and easy to understand. Use EXAMPLE.hideCursor() to initiate the hiding of the cursor and EXAMPLE.showCursor() to stop the event. Replace #game with the desired div element ...

It's more organized to use the on and off methods along with named functions rather than anonymous functions.

I am aware that the original poster did not specify a preference for JQuery solutions, but personally, I find it beneficial to explore various methods to broaden my knowledge.

Answer №5

To ensure that no characters are lost when moving out of the screen-saver in my kiosk apps, where data is typically inputted via a barcode scanner or RFID reader and instantly bring the screen back on, I have implemented the following code snippets. This includes using a transparent cursor file and disabling all power saving options on the host OS to prevent any delays. Although tested on Chrome 12, it should work on other browsers as well. There isn't any browser-specific code involved; Chrome just happens to be the most convenient for launching into kiosk mode.

The code has some messy parts specifically designed for iterating through INPUT elements to preserve their default white background.

If your app involves images, colored text, or other objects, you will need to adapt the code accordingly. My focus is on building data acquisition apps with simple black text displays to avoid screen burn-in by setting the page background to black.

While this could be achieved with CSS applied via JavaScript, the current method works efficiently and can easily be copied and pasted where needed.

<body onkeydown="unSS();" id="thePage">

By having unSS triggered on keydown events within the body, the timer gets reset every time a key press is detected.

<script type="text/javascript">

var ScreenSaver = 10; // minutes

SS(); // initiate the timer

function unSS()
{
    document.getElementById('thePage').style.background='White';
    for (var i = 0; i < document.getElementsByTagName('INPUT').length; i++)
        {
            document.getElementsByTagName('INPUT')[i].style.background='White';
        }

    //bring back the default cursor
    document.getElementById('thePage').style.cursor = 'default';

    ScreenSaver=10;
}

function SS()
{
    ScreenSaver = ScreenSaver-1;  

    if (ScreenSaver<=0)
        {
            document.getElementById('thePage').style.background='Black';
            for (var i = 0; i < document.getElementsByTagName('INPUT').length; i++)
                {
                    document.getElementsByTagName('INPUT')[i].style.background='Black';
                }
               
               document.getElementById('thePage').style.cursor = 'url(transparentCursor.cur)';
        }

    setTimeout("SS();",60000);  
    }
...

Answer №6

If you're looking for a way to determine if a user is idle or active, consider using the jquery plugin idletimer.

Answer №7

To address the intermittent no-cursor issue, I have devised a simple solution by adding a transparent

<div id="overlay"> </div>
as the final element on the webpage. Here are the CSS style properties to apply:

#overlay {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
  background-color: transparent;
  cursor: none;
  margin: 0;
  padding: 0;
  border: 0;
}

Using javascript, you can toggle the visibility between "visible" and "hidden". When the layer is set to "visible", it will conceal the cursor, and when set to "hidden", the cursor will be visible again.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for transforming a 9-digit uploaded data into a 10-digit number using Angular

As someone who is new to Angular, I am working with an Angular UI where users upload a CSV file containing 6 columns of data. Before invoking the .NET API, I need to modify the data in the 1st column: if a value consists of 9 digits, it should be changed t ...

Is there a way to transform iframe to encoded javascript?

Is there a way to change an iframe src into encoded JavaScript so that the real URL cannot be found when viewing in page source? Alternatively, does anyone have access to the script available at ? I am interested in using this site but do not have the so ...

Tips for customizing the background color and image of a toaster

Looking to modify the background color and image based on the else condition (toaster.error) success: function (data) { if (data.message != ""){ toastr.success(data.message); ...

Can you explain the function of mdLiveAnnouncer in Angular Material and how it operates?

Could someone provide an explanation of $mdLiveAnnouncer using this code snippet? module.controller('AppCtrl', function($mdLiveAnnouncer) { // Making a basic announcement (Polite Mode) $mdLiveAnnouncer.announce('Hey Google'); // ...

The JSColor onChange event is throwing an error indicating that the function is not defined

When attempting to use the onChange event for JSColor to call a function, I consistently encounter an error indicating that the function is not defined. The code snippet below illustrates the issue: export class NavBar extends React.Component { constr ...

Anchor checkboxes

I am dealing with a large number of checkboxes that are linked to anchors. Whenever a checkbox is clicked, it navigates to the corresponding anchor on the same page. Is there a more efficient way to implement this? With around 50 checkboxes, my current cod ...

Using the v-for directive to loop through a list of items and adding a v-autocomplete with

I am facing a challenge with using a dropdown menu within a loop to select the region for each office in my list of offices. The problem lies in passing the index value to the updateRegion method so that I can correctly associate the selected region with t ...

What is the best way to make the first LI elements stand out in a nested structure by applying bold

I had an idea like this: #list li > a { font-weight: bold; } However, I only want the top level items to be made bold, not nested LI's within LI's -- hope that makes sense?? :) EDIT | <ul id="list"> <li><a href="#"& ...

Buttons aligned vertically alongside an input text field

I am trying to align two buttons vertically under an input text box with the middle aligned. This is what I have done so far: jQuery(document).ready(function($) { // Implementing bootstrap minus and plus plugin // Reference: http://jsfiddle.net/lael ...

In React conditional return, it is anticipated that there will be a property assignment

What is the optimal way to organize a conditional block that relies on the loggedIn status? I am encountering an issue with a Parsing error and unexpected token. Can someone help me identify what mistake I am making and suggest a more efficient approach? ...

What steps can you take to guarantee that a service worker consistently caches the same set of files?

My progressive web app (PWA) is made up of various files like index.html, manifest.json, bundle.js, and serviceWorker.js. Updating the app involves uploading all these files to my host, which in my case is Firebase. I use firebase deploy for this purpose. ...

Struggling with rendering an HTML element utilizing jQuery's attribute functionality, encountering issues exclusively in Internet Explorer version

I need assistance with generating and inserting an HTML element using jQuery. In my code, I am including a class attribute for the element as shown below: jQuery('<li></li>', { class: "myClass" }); However, when testing in IE ...

What is the best method for incorporating information into an existing object when it is currently empty?

When it comes to data removal, my method involves locating the element using findIndex and marking it as a null value in isInArray. However, if no such data exists, how can I add it to an empty element starting from the first one? For instance, if the fi ...

What is the best way to design a grid with various squares in React Native?

Here's the design I aim to achieve: I am looking to implement the above layout in react native and ensure it is responsive on all screen sizes. I attempted using flexbox but couldn't figure out how to make the boxes square shaped. The code provi ...

The information seems to not be getting transferred to the req.body variables from the HTML form

Within my server-side settings using knex and express, I have defined the following function: // POST: Create new users app.post('/add-user', (req, res) => { const {firstName, lastName, emailAdd, gender, dob, password} = req.body; cons ...

Display the number of items that have been filtered as soon as the Mixitup page loads

Currently, I am utilizing MixItUp 3 for sorting and filtering items, with the goal of displaying the count of items within each filter category upon the initial page load. Despite attempting a solution found on SO (mixitup counting visible items on initial ...

Importing a CSV file from the web (Google Sheets) and converting it into a JavaScript array

I am working with a Google spreadsheet ( https://docs.google.com/spreadsheet/ccc?key=0Agymc2_-gI59dGxvRnZoRzNuNENIUE9kZ0h6WExxSXc&usp=sharing ) where I store my golf scores after each round. My goal is to import this data into my JavaScript file and ...

Generate a JSON Object array by collecting data from various elements to make it dynamic

Seeking assistance in creating a dynamic array of JSON objects from the values of various elements. Below are some examples of these elements. There are more elements contributing to the JSON values, but I don't want to repeat the same code three time ...

Calculating the sum of integer values from v-models in Vue 2

I am currently working with Nuxt version 2.8.1 There are a total of 100 input fields in my form, all of which are number inputs. My goal is to calculate the sum of all these numbers to get the total. This is what I have tried so far: computed: { to ...

Establish the style of a div using the value of an Angular scope

I am working on displaying the percentage of some activity using a horizontal div. The setup involves an outer div with a width of 100% and an inner div. I need to fill the inner div with a background color based on the percentage value obtained from the c ...