Is there a way to confirm if all div elements have a designated background color?

I have a scenario where I have dynamically added several divs with a specific class to my webpage. These divs change color when the user hovers over them. I am trying to trigger a specific function once the last div has been set to a particular background color, but despite my efforts, I have not been successful so far. Any insights or help would be greatly appreciated. Here is the code snippet from my latest attempt:


var counter=0;
$(".orb").each(function () {
    if ($(this).css("background-color") === "#ede74a") {
        counter=counter+1;
    }
});
if (counter === orbarray.length) { //all backgrounds have been set
    executeFunction();
}

Answer №1

To simplify things, consider adding a class to the elements and keeping track of that class.

$(document).on('mouseenter','.orb',function(){ 
    var $orb = $(".orb"); 
    $(this).addClass('hovered');
    if($orb.filter('.hovered').length === $orb.length){
       alert('All hovered!');
       executeFunction();
    }
});

The mentioned colors are unclear, but this method can be adjusted for multiple classes if necessary.

Keep in mind that browsers store colors as either rgb or rgba, not as hex values.

Answer №2

The code you've provided lacks clarity regarding the value of orbarray. It's also unusual that you are checking the equality of counter with the length of that array outside of the $.each() callback.

However, if I understand correctly, you want to trigger a specific function when the last <div> is hovered over. This indicates the need for an event handler for the mouseenter event, and then verifying in that handler whether all elements have been hovered over. Using a class instead of inline CSS will provide a more efficient way to track hovered elements.

Consider the following example:

function checkOrbs() {
  var $orbs = $('.orb'),
      $activeOrbs = $orbs.filter('.active');

  if ($orbs.length === $activeOrbs.length) {
    executeFunction();
  }
}

$('.orb').on('mouseenter', function(e) {
  var $target = $(e.target);

  $target.addClass('active');

  checkOrbs();
});

Simply apply your background color using CSS:

.active {
  background-color: #ffcc00;
}

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

Ways to retrieve the parent DIV's width and adjust the child DIV's width to match

Attached is my question with the HTML and a screenshot. Within a DIV container (DIV with ID=ctl00_m_g_a788a965_7ee3_414f_bff9_2a561f8ca37d_ctl00_pnlParentContainer), there are two inner DIVs - one for the left column TITLE (DIV ID=dvTitles) and the other f ...

Can you help me understand how to ensure the CSS translate feature lands in a specific div, no matter its initial position?

I'm facing a roadblock in my journey to create a card game. The issue arises at the final stage of the Translate function implementation. In this game, the player is dealt 30 cards (I've simplified it to four for ease of programming), and upon cl ...

Customize the popover in React Material-UI to your liking

I am currently utilizing a Select component within my application. https://i.stack.imgur.com/hjXlY.png I have created a custom modal component that I wish to display instead of the default list items when the select is clicked. Is there a method to overr ...

Preventing the Rendering of Inline-Block Whitespace in Web Browsers

Essentially, in my attempt to create a four-column layout, I have the following HTML code: <div> <div>A column</div> <div>A column</div> <div>A column</div> <div>A column</div> </div ...

The argument type does not match the parameter type partial<>

While attempting to validate my Ionic React form, I encountered an error when calling the validationSchema within the useForm method. The specific error message received is as follows: Argument of type '{ validationSchema: ......' is not assignab ...

What is the best way to send a React prop that is buried deep within a JSON structure?

Currently, I am in the process of creating a product table to showcase items for a store. The headers of this table include: id, title, imagePath, newPrice, oldPrice. To accomplish this, I have developed an ItemTable component within my React application t ...

Looking to include a badge within the nebular menu

Can someone assist me with adding a badge to the Nebular menu to display the inbox count dynamically? Any help would be greatly appreciated. Thanks! import { NbMenuItem } from '@nebular/theme'; export const MENU_ITEMS: NbMenuItem[] = [ { ti ...

Assigning multiple identifiers to a single element

Multiple posts have emphasized the importance of using an ID only once. But, I'm facing a situation where I need to pass 2 PHP variables to my JavaScript. I initially thought of using document.getElementById, but since IDs must be unique, this approa ...

Understanding the timing of records being returned via an Observable in Angular's ngOnInit

In my Angular 2 application, I am using an observable to keep track of an array of records. As the results of this observable are stored in the variable "records", I am utilizing *ngFor="let record of records" to iterate over and display them in my view. ...

"Implement a function to append a new item to all JSON objects in an array if they share a common value with a different JSON object in the array using

Hi there, I'm new to Vue Js and I'm currently working on adding or merging new items in all JSON objects within an array that share the same value with another JSON object. I know how to push a new JSON object into an existing one, but I would re ...

Why does the lazy loading feature keep moving the background image around?

While trying to incorporate lazy loading on my website, I encountered an issue where the image position would change after it was fully loaded and made visible. I experimented with rearranging the order in which my JavaScript and CSS files were called, bu ...

Troubleshooting Symfony2 and Assetic: Why are my CSS-linked images not loading?

I've encountered an issue with my CSS sprite sheet that my CSS file seems unable to locate the image. Despite following the provided solution here, I'm still facing the same problem. The directory structure of my bundle is as follows: src/ v ...

Column div being obscured by footer

My footer is causing overlap issues with the div above it on my mobile website. Here's a visual representation: Current view on my phone: https://i.stack.imgur.com/RpvWM.png Desired view: https://i.stack.imgur.com/KHVcm.png The code for the are ...

Is there a way to modify the background color of a button once it has been clicked, specifically using JavaScript?

I am looking to change the background color of a button that I have clicked on in my code. Do I need to use loops and conditions for this task? I attempted to access the first index, but I am unsure how to change the background color of other buttons. l ...

The CSS menu dropdown fails to function properly on desktop view when there is longer content present

I attempted to merge two different navigation bars, one sticky and the other responsive. The goal was to combine https://www.w3schools.com/howto/howto_js_navbar_sticky.asp with https://www.w3schools.com/howto/howto_js_responsive_navbar_dropdown.asp Curr ...

Use JQuery's $ajax to exclusively retrieve items that have a date prior to the current date

In my jQuery code, I have a function called fetchResults that makes an AJAX request to '/Search/GetResults' and returns the JSON-formatted data. This endpoint does not require any specific criteria to be passed. The returned data looks like this ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...

When clicking on the material-ui autocomplete feature in a React JS application, a blank page unexpectedly opens

I am encountering a problem where, upon clicking the Autocomplete component imported from material-ui, it displays a blank page. const defaultProps = { options: catalogs, getOptionLabel: (option) => option.catalogsLink, }; <Autocomplet ...

Is there a way to shift this div to the bottom and incorporate some quirky pop-up squares?

I am struggling to figure out how to move this div to the bottom. Additionally, I want to create temporary pop-up squares (simple divs) in random directions that will disappear after 50ms. My attempt to float this box to the bottom did not yield the desir ...

PHP is used to receive JSON data sent via Ajax for fetching information

I have a jQuery code that outputs JSON data and I am looking to send this data to a URL and retrieve it using PHP. Code: JSON.stringify(showtimes) Output: [{"show_id":"1","movie_id":"20","cinema_id":"10","status":"0","times":"00:00"},{"show_id":"2","mo ...