Adjust the cursor style using Javascript

I am currently working on a paint software program and I have a feature where pressing the ctrl key while moving the mouse turns on the eraser. However, when the key is pressed, I want the cursor (currently a crosshair) to change to none. I have tried implementing

document.body.style.cursor = "none"
and
document.getElementById("canvas").style.cursor = "none"
, but unfortunately, both methods did not work. I need to achieve this using Javascript, so please do not suggest using Jquery.

Below is a snippet of the code I have attempted so far:

<!doctype html>
<html lang="en">
<head>
<style>
body { 
            /* 
                CSS selector to style all <body> elements on the page
            */
            background-color: #c0c0c0; 
        }

        #cw1MainContainer { 
            /* 
                CSS selector to style the element with id="cw1MainContainer"
            */
            position: absolute; 
            left: 20px; 
            top: 20px; 
        }

        canvas { 
            /* 
                CSS selector to style all <canvas> elements on the page
            */
            background-color: #fafafa; 
            border: 1px solid #a0a0a0; 
            cursor: crosshair; 
        }

        #box {
          pointer-events: none;
          background-color: #000000;
          width: 5px;
          height: 5px;
        }
    </style>

    <script>
        // Javascript code
    </script>

</head>
</html>

Any assistance in resolving this issue would be greatly appreciated. Thank you

EDIT: here's my HTML code: `

    <div id="cw1MainContainer">
        <div id="cw1CanvasContainer">
            <canvas id="cw1Canvas" onmousemove="fnTrackMouse(event);" onkeypress="fnBrushSize(event);"></canvas>
            <div id="box" style="border: 1px solid #000000; position:absolute;" />
        </div>
    </div>      

</body>`

Answer №1

If you're encountering issues with accessing the DOM before it renders, take a look at the code snippet provided below.

function adjustCursor(){
  var $canvas = document.getElementById("myCanvas");
  $canvas.addEventListener('mouseover', function(e){
    if(e.ctrlKey){
      $canvas.style.cursor = 'none';
    } else {
      $canvas.style.cursor = 'crosshair';
    }
  })    
}
#myCanvas{
  cursor: crosshair;
  width: 100px;
  height: 100px;
  background: skyblue;
}
<!DOCTYPE html>
<html lang="en">
<head>
  
  <!--  Meta  -->
  <meta charset="UTF-8" />
  <title>Customizing Cursor Styles with Javascript</title>
  
  <!--  Styles  -->
  <link rel="stylesheet" href="styles/index.processed.css">
  <script src="scripts/index.js"></script>
</head>
  <body onload="adjustCursor()">
    <div id='myCanvas'>
    </div>
  </body>
</html>

Answer №2

Instead of using document.body, try using document.documentElement for your solution.

The issue may have been caused by the DOM's own styling overriding the changes you were trying to make, thanks to specificity in CSS.

Simply adding *{cursor: none!important;} in your CSS should resolve the problem.

Below is the JavaScript code:

function hide(){
 document.documentElement.style.cursor = "none";
}
<button onclick="hide()">Try me</button>

EDIT!

If you prefer adding *{cursor: none!important;} to your stylesheet, you can utilize the following code:

function hide(){
 var css = document.createElement("style");
 css.type = "text/css";
 css.innerHTML = "*{cursor: none!important;}";
 document.body.appendChild(css);
}
<button onclick="hide()">Try me</button>

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

Conflicting styles between Bootstrap and Formstack are causing radio buttons to appear only partially visible

Encountering a conflict between Bootstrap (4.1.3) and Formstack CSS when trying to embed a form in a website. The radio buttons are not fully visible, with the issue located in the "label" class ("fsOptionLabel"). Adjusting the line height provides a parti ...

Encountering a "require is not defined" error when trying to launch a Selenium

I have developed a basic selenium application and now I am looking to implement a graphical user interface for it. Here is the code snippet: index.html: <html> <head> <meta charset="UTF-8" /> <title>Selenium Ap ...

Exploring the possibilities of applying CSS to customize the color of various elements

Is there a way to set the color of elements in CSS so that it applies to everything such as fonts, borders, and horizontal rules when applied to the body? How can I accomplish this effectively? ...

Centering Text in CSS and HTML

Today I am pondering over how to align text horizontally on my website. The layout of us.mineplex.com's forums, shop, and title is perfectly aligned in a horizontal manner. I have tried to figure it out on my own but need some help. Thank you. CSS: ...

The HTML textarea is not updating properly when using jQuery's keypress event

I am facing an issue with my forms on a webpage, each containing an html textarea: <textarea name="Comment" class="inputTextArea">Hello World!</textarea> There is a javascript event handler that automatically submits the fo ...

Unable to refresh JSON data in Datatables

Ensuring this operation is simple, I am following the documentation. An ajax call returns a dataset in JSON format. The table is cleared successfully, but even though data is returned according to the console statement, the table remains empty after the su ...

Display a preloader image while waiting for the content to load using jQuery or AJAX

Hey there, I could really use some help with a little issue. I've been trying to use the click() and load() functions to bring my content into a specific CSS class. $("#feed").click(function(){ $(".homefeed").load("feedcontainer.php"); ...

Tips on adding line breaks after periods that are not at the end of a sentence in HTML text nodes with regular expressions

Looking to craft a regex that can identify all periods not enclosed in quotes and not followed by a '<'. This is for the purpose of converting text into ssml (Speech Synthesis Markup Language). The regex will be utilized to automatically inse ...

Leveraging async/await to handle the insertion of SQL data

function Scan_Insert_Recursive (dir_path) { //scans dir_path recursively and inserts file path into a temporary list Scan_Recursive(dir_path, (err, files) => { //using npm recursive_readdir for scanning if(err) { console.log(err) ...

Having trouble getting Bootstrap 5 to work with a position-relative row?

I am having trouble placing the * sign on the left side. Whenever I try to do so, it only works if I remove the row class. <!doctype html> <html lang="fa" dir="rtl"> <head> <meta charset="utf-8"> ...

Encountering 'Illegal Invocation' error while running a basic script

Exploring the Speech Recognition API has been on my to-do list, so I decided to create a simple page that initiates recognition when clicking on the body element. Here is a snippet from my scripts.js file: var recognition = new window.webkitSpeechRecognit ...

Disarrayed image in absolute position on my webpage

I have a website with an auto-resizing background, but I am struggling to have a fixed black bar at the bottom of the page. Everything looks good when the browser window is maximized, but as soon as you scale it down and start scrolling, the black bar alm ...

What is the best way to save the values of all the input fields in a datatable, excluding any fields that are empty?

$('form').on('submit', function(e){ var form = this; // Encoding a set of form elements from all pages as an array of names and values var params = table.$('input').serializeArray(); // Iterating over all form ...

Communicating information to components in Next.js

I am struggling to pass the fetched data from my API to the canvas component. It appears that the data is available in the handleSubmit() function but out of scope for the canvas prop. Any help would be greatly appreciated. Thank you. I have a datepicker ...

The error message "File is not defined" in the context of express is throwing

I am attempting to convert a base64 string into an image file and send it to Firebase through Express. Everything is functioning correctly on the frontend, except for this particular section: const convertBase64ToFile = (base64String, fileName) => { ...

Showing or hiding components within ReactJS based on conditions from other components

A custom hook has been created to toggle the visibility of a list when a button is clicked. Below is the snippet of the custom hook: import { useEffect } from "react"; import { useState } from "react"; function useVisibilityStatus() { ...

Trouble with jQuery dialog not triggering when Enter key is pressed

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <form action="" id="formID" name="formID" > <input type="text" id="filename" class="validate[required]"/> <script type="text/ja ...

Issue with Angular Script not functioning upon reopening the page

I recently completed my first website, which can be found at Despite my efforts, I've encountered an issue that has me stumped. When you navigate to the certificate page, you should be able to input your name onto the certificate. However, if you sw ...

The search bar fails to display all pertinent results when only a single letter is inputted

How can I create a search functionality that displays array object names based on the number of letters entered? When I input one letter, only one result shows up on the HTML page, even though the console.log displays several results. The desired output is ...

Is there a way to place my searchbox in the top right corner of the page?

I am currently working on creating a search function for my list of products. However, I have encountered an issue where the searchBox is not appearing in the top right corner as intended. Despite trying various solutions, I have been unsuccessful in movin ...