Is it possible to dynamically assign a CSS class to a DOM element during a drag operation while the mouse button is held down?

I am currently working on developing a unique pathfinder visualizer. My progress so far includes creating a grid of size 16x45 using the function below:

export const drawBoard = () => {
  const boardContainer: HTMLDivElement | null = document.querySelector(
    ".board-container"
  );

  if (boardContainer != null) {
    // 16x45 board
    for (let i = 0; i < 16; i++) {
      const row = document.createElement("div");
      row.classList.add("row");
      for (let j = 0; j < 45; j++) {
        const col = document.createElement("col");
        col.classList.add("col");
        col.setAttribute("data-row", `${i}`);
        col.setAttribute("data-col", `${j}`);
        row.appendChild(col);
        col.addEventListener("click", function () {
             this.classList.add("wall"); // Add a wall class to the CSS
        });
      }
      boardContainer.appendChild(row);
    }
  }
};

The function described above generates the grid depicted in the document linked below:

https://i.sstatic.net/oBxjB.png

It is possible to extract the x and y coordinates of a specific tile, as shown in the image here:

https://i.sstatic.net/xZAs5.png

Every tile has been assigned a click event to add a wall CSS class and change its color to black upon clicking.

Now, my inquiry is as follows:

Is there a way to apply the CSS wall class to the tiles while the mouse button is held down? Is there a specific event listener for this task?

My ultimate goal is to achieve the following effect:

https://i.sstatic.net/MzL5s.gif

Answer №1

Tracking the status of the mouse is crucial, especially when handling the mousemove event. Implementing a solution similar to the following should do the trick:

//variable to store mouse down status
let isMouseDown = false;
document.addEventListener("mousedown" () => isMouseDown = true);
document.addEventListener("mouseup" () => isMouseDown = false);

export const renderBoard = () => {
  const container: HTMLDivElement | null = document.querySelector(
    ".board-container"
  );

  if (container != null) {
    // create a 16x45 board
    for (let i = 0; i < 16; i++) {
      const row = document.createElement("div");
      row.classList.add("row");
      for (let j = 0; j < 45; j++) {
        const cell = document.createElement("col");
        cell.classList.add("col");
        cell.setAttribute("data-row", `${i}`);
        cell.setAttribute("data-col", `${j}`);
        row.appendChild(cell);
        
        //add mousemove event listener
        cell.addEventListener("mousemove", function() {
          //add wall class if mouse is down
          isMouseDown && this.classList.add("wall")
        });
        cell.addEventListener("click", function() {
          //no need to check for mousedown on click
          this.classList.add("wall")
        });
      }
      container.appendChild(row);
    }
  }
};

Answer №2

If you want to accomplish your goal, you can utilize the mousedown event. Additionally, there is also a mouseup event available for use.

For more information on various events, feel free to check out this reference guide.

https://developer.mozilla.org/en-US/docs/Web/Events

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

What is the best way to use command line arguments within a Node.js script?

As a newcomer to the world of programming, I find myself struggling to make progress despite putting in significant effort. Although it may seem like a trivial question, my lack of progress is becoming frustrating. Currently, I am working on a node.js scr ...

What could be causing my selenium tests to fail on travis-ci even though there have been no code changes, when they are passing successfully

I'm facing a tough challenge trying to troubleshoot a selenium test that passes when run locally but not on travis. Reviewing the travis build logs, I noticed that the test was passing in build #311 but started failing at build #312. It seems like th ...

What is the best way to adjust a Checklist's width to match the width of its parent Dropdown in Dash Plotly?

At the moment, I am facing an issue with setting the width of a checklist from Dash Core Components to match the width of the dropdown menu it is placed in. Here's a glimpse of how it appears currently: https://i.sstatic.net/mjzAd.png Below is the P ...

You are unable to call upon an object that may be of type 'undefined' in typescript

Among all the other inquiries on this topic, my issue lies with the typescript compiler seeming perplexed due to the following code snippet: if(typeof this[method] === "function"){ await this[method](req,res,next) } The error message I am en ...

Set the property state to false based on the value of another property in Mongoose Express NodeJS

I am trying to update the status property of a sale based on the outstandingBalance value being equal to 0. Currently, I am able to successfully update the "outstandingBalance", but I want to automatically change the status if it reaches 0. Below is the c ...

How can I modify the dot colors on a graph using chart.js?

Need assistance with changing the color of graph data points https://i.sstatic.net/QGJBv.png Here is my JavaScript code snippet I have successfully created a graph using chart.js. However, I now want to differentiate data points by displaying different c ...

Unable to save captured signature image during saveEvent function in React Native

I am a beginner in the world of React Native and I am facing an issue with saving a signature image. It seems like the function responsible for this task is not being called properly. I suspect there might be an issue with the onPress event handler, as whe ...

Looking to dynamically display users added to an array in a table using Angular and JavaScript?

As a newcomer to javascript and angularjs, I recently attempted to build a table that would display all users in an array dynamically as new users are added through a form. However, each time I run my code, I encounter the error message "Fill out the entir ...

How can I adjust the size of the renderer in Three.js to fit the screen?

Encountering issues with the code snippet below: //WebGL renderer renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); //TODO: set optimal size document.body.appendChild(renderer ...

Next.js React Hydration Issue - "Anticipated a corresponding <a> within the server HTML <a>"

Currently, I am encountering a hydration error while working on my Next.js project. The specific error message that keeps popping up is: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected serv ...

What is the reason behind Angular not allowing users to define @Output events that begin with 'on'?

While developing a component, I defined an output EventEmitter named onUploaded. However, Angular flagged an error instructing me to use (uploaded) instead. This restriction is due to security concerns, as bindings starting with 'ono' pose risks. ...

Learn the process of zipping a folder in a Node.js application and initiating the download of the zip file afterwards

After encountering issues with the latest version of the npm package adm-zip 0.4.7, I reverted to an older version, adm-zip 0.4.4. However, despite working on Windows, this version does not function correctly on Mac and Linux operating systems. Additionall ...

Determine whether a specific key exists in the formdata object

Can I check if a key in the formdata object already has a value assigned to it? I am looking for a way to determine if a key has been previously assigned a value. I attempted something like this but did not get the desired outcome data = new FormData(); ...

Misalignment of social media buttons is causing display issues

I have arranged my Social Media Div to the right of my Review Div: http://jsfiddle.net/eYQWE/ The issue: the social media buttons in My Social Media div are not staying in a straight line and keep dropping below my Review Div. Do you have any suggestions ...

PHP issues caused by Ajax form compatibility

I'm currently working on developing an upload website and I've encountered some challenges while trying to implement an upload progress bar. The Ajax form in my scripts seems to be causing issues with the PHP code, preventing the file from being ...

What is the best way to implement a counter with setInterval in Angular?

As a beginner in Angular, I am trying to utilize the setInterval function to count numbers, but I am facing difficulties in achieving success. Can someone provide assistance with this issue? (Apologies for any grammar mistakes in my English.) Thank you in ...

Retrieve all services within a Fargate Cluster using AWS CDK

Is there a way to retrieve all Services using the Cluster construct in AWS CDK (example in TypeScript but any language)? Here is an example: import { Cluster, FargateService } from '@aws-cdk/aws-ecs'; private updateClusterServices(cluster: Clus ...

The leaflet_Ajax plugin is constantly searching for the default marker symbol located at js/images/marker-icon.png

Although I'm relatively new to Leaflet, I have experience creating interactive maps in the past. Recently, I've been working on a project involving displaying GPS data from a UAV. The UAV transmits location information to a server, which then ret ...

Configuring VS Code's "tasks.json" file to compile all .ts files can be done by following these steps

Apologies if this question has been asked before, but could someone please redirect me to the relevant thread if so. I am wondering if it is possible to set up VS Code's "tasks.json" to automatically compile all .ts files within a folder. Currently, I ...

Maximizing Efficiency: Utilizing a Single jQuery Function to Retrieve Specific Values

I have a webpage with select menus for choosing user type, minimum age, and maximum age. I want to select options and send values as an object array to ajax. Initially, the getAjax function is working when the page loads. However, it stops working when I c ...