Having trouble getting CSS styles to work properly in conjunction with Javascript code

Currently, I am developing a feature on a canvas that covers the entire webpage's width and length. In this canvas, I have the ability to create boxes by clicking down anywhere on the canvas, dragging my mouse in any direction, and upon releasing the click, the box is created. This functionality is similar to how selection works on a desktop, with the difference being that when the mouse button is released, the selection box is drawn on the canvas.

The issue I am facing involves updating the cursor behavior when hovering over the boxes I have created. These boxes are stored in an array named panels.

function mouseOverPanels(e) {
        var mouseX = e.clientX, mouseY = e.clientY;

        // iterate through all the panels
        for (var i = 0; i < panels.length; i++) {
            // check if cursor is within the boundaries of a panel to update its appearance
            if ((mouseX >= panels[i].x && mouseX <= panels[i].x + panels[i].width) && (mouseY >= panels[i].y && mouseY <= panels[i].y + panels[i].height)) {
                canvas.style.cursor = "pointer";
            }

            // if not, set the cursor to "crosshair" (default)
            else canvas.style.cursor = "crosshair";
        }
    }

The current implementation of this code is functional. Upon creating a panel, the cursor updates correctly when hovering over it, based on its position. However, the problem arises when multiple panels are created. The function seems to only update the cursor for the latest panel created, neglecting the previous ones. Although it detects the mouseover event on the previous panels, it fails to update the cursor within their boundaries.

Do you have any ideas or suggestions? A solution is required to be implemented solely using JavaScript without relying on external libraries.

Answer №1

The reason for this behavior is that your if/else statement takes place within each iteration of the loop. Therefore, only the outcome from the final iteration matters, similar to if you had simply referenced panels[panels.length - 1] without a loop.

Instead, consider establishing a default value and updating it when encountering a relevant entry (then exiting the loop):

// iterate through all panels
var cursorType = "default";
for (var i = 0; i < panels.length; i++) {
    // check if mouse cursor intersects with current panel bounds
    if ((mouseX >= panels[i].x && mouseX <= panels[i].x + panels[i].width) && (mouseY >= panels[i].y && mouseY <= panels[i].y + panels[i].height)) {
        cursorType = "pointer";
        break;
    }
}
canvas.style.cursor = cursorType;

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

After the build process, Nextjs Sitemap is eliminating the /en/ from all newly generated web links

Utilizing Strapi to pull data in JSON format. For instance, a typical website link appears as follows: https:/ /www.some-site.com/some-link What happens to the links once the post build is completed on my Nextjs project: <url><loc>https://web ...

When using Jest, the mongoose findOneAndUpdate function may return null values for both error and document

I've been struggling with Mongoose's findOneAndUpdate method as it doesn't seem to provide any useful information. I have tried accessing the Query returned from calling it (stored in updatedUser), but all it returns is null. Adding a callba ...

Is there a way to make the footer adapt to the varying heights of the grid sections as they grow in size?

Currently, I am facing an issue with the positioning of the page footer. Despite my efforts, it does not remain at the bottom as intended. Please refer to the image for a visual representation of the problem. How can this be rectified? It is worth noting ...

CSS or jQuery: Which is Better for Hiding/Showing a Div Within Another Div?

Show only class-A at the top of the page while hiding all other classes (x,x,c). Hide only class-A while showing all other classes (x,x,c). Is it possible to achieve this? <div class="x"> <div class="y"> <div class="z"&g ...

Error: Unable to access the 'nom_gr' property of null - encountered in Chrome

<ion-col col-9 class="sildes"> <ion-slides slidesPerView="{{nbPerPage}}" spaceBetween="5"> <ion-slide *ngFor="let slide of lesClassrooms; let i = index" (click)="saveCurrentSlide(i)"> ...

The Javascript function is designed to function exclusively with onclick events or setTimeout functions

I am currently working on a website that I want to be responsive to the window size. However, I am facing an issue with vertical alignment. I have created a jQuery function to handle this, and it works well for divs with images but not so well for a div wi ...

Use JQuery to constantly monitor for any changes in HTML Div

I am dealing with a browser-based chat application where separate div elements are generated for each chat conversation. An external module oversees the entire chat process, and I do not have access to its underlying code. It is important to note that the ...

Turning spring form data into a JSON object via automation (with a mix of Spring, jQuery, AJAX, and JSON)

Recently, I've set up a spring form that utilizes ajax for submission. Here's an overview of my form... <form:form action="addToCart" method="POST" modelAttribute="cartProduct"> <form:input type="hidden" ...

Accessing Child Properties in Parent Component using Typescript

New to the world of Typescript! Imagine having a component called TitleSubtitle that consists of both a Title and a Subtitle component. The Title component comes with props: interface TitleProps { text: string; } The Subtitle component also has props ...

Tips for implementing Papa Parse to parse CSV files using JavaScript

I've been exploring their API without much luck. My goal is to extract data from CSV files that are sent to the client upon server entry. Here's the code snippet I attempted: // Attempting to parse local CSV file Papa.parse("data/premier leagu ...

How to append double zeros to a number in Material UI Data Grid

I'm currently working on a React.js application that utilizes the DataGrid component from the Material UI (MUI) library to display data. My challenge lies in formatting full numbers with trailing zeroes for better clarity. For example, displaying 625 ...

Need help with a countdown function that seems to be stuck in a loop after 12 seconds. Any

I am facing an issue with a PHP page that contains a lot of data and functions, causing it to take around 12 seconds to load whenever I navigate to that specific page. To alert the user about the loading time, I added the following code snippet. However, ...

Unable to update a single object within an array using the spread operator

I am currently working on updating an object within an array and have encountered some issues. In my initial code, I successfully updated a specific property of the object inside the array like this: var equipment = this.equipments.find((e) => e.id === ...

What is the best method for implementing pagination in Larvael with React using Inertia?

Is there a way to paginate in react using inertia with laravel? When pulling paginated data, I use the following code: $contacts = Contact::orderBy('name', 'asc')->paginate(10); return Inertia::render('Contacts/index', [ ...

Rendering ng-include before setting the source

Is there a way to prevent the ng-include directive from trying to render before a value on scope is set? Consider the following example: <ng-include src="'./lib/templates/' + $parent.currentEditable.editTemplate"></ng-include> It s ...

Utilizing Angular 4 alongside ng-sidebar to incorporate the class "right"

Just started using ng-sidebar in my Angular 4 project, but I'm a bit lost on where to place the "ng-sidebar--right" class. Could someone please guide me through this small issue (I'm new to this, so apologies in advance). Here's a snippet of ...

Trying out asynchronous testing using Mocha and Sinonjs for the first time

In my current project, I am utilizing a custom micro framework developed by our team, where we make use of Mongoose. To handle the mongoose object, we have implemented a modelfactory that provides us with a corresponding model based on the mongoose name o ...

Background cutting off right side of HTML website

While updating my supervisor's university website, I noticed a problem with the responsiveness. When resizing the browser window, a horizontal scroll bar would appear and the right side of the website would get covered by the background. On mobile dev ...

Having trouble understanding how to display an HTML file using Next.JS?

Currently, I am working on a project that involves utilizing Next.JS to develop a webpage. The main goal is to display a PDF file on the left side of the screen while integrating Chaindesk on the right side to create a chat bot capable of extracting inform ...

The Ajax PHP file uploader is experiencing technical difficulties

I am currently working on an ajax image uploader that is supposed to work automatically when a user submits an image. However, I've encountered an issue where the uploader does not function as expected when I try to rename the images for ordering purp ...