jQuery CSS Issue: Background Not Updating

Attempting to transform a grid of small square divs by assigning them random background colors, I am facing an issue.

Although my syntax appears correct and the console is not reporting any errors, it seems like the .css() method refuses to accept the genColor function I have implemented.

While looking for a solution, I came across this thread which shares similarities with my situation, but unfortunately, the proposed fix did not resolve my problem.

function genColor() {
'use strict';
var hexes = '0123456789ABCDEF'.split('');
var color = '#';

for (var i = 0; i < 6; i++){
    color += hexes[Math.floor(Math.random * 16)];
}//end for loop

return color;

This function is then utilized in the following code snippet:

function highlightSquare(){
'use strict';

$('.square').on('mouseenter', function () {
    $(this).css('background', genColor()); 
});

If anyone can provide assistance, I would greatly appreciate it. Despite encountering examples that suggest otherwise, I am unable to pinpoint why this specific implementation is failing.

On a side note, the inclusion of 'use strict'; serves the purpose of preventing JSLint warnings within the Brackets editor, without directly impacting the functionality of the aforementioned code.

Answer №1

It appears that there may be an issue with the usage of Math.random as it is a function and should be called as Math.random(). Additionally, ensure that the event listener is assigned outside of any functions in your code.

function genColor() {
  'use strict';
  var hexes = '0123456789ABCDEF'.split('');
  var color = '#';
  for (var i = 0; i < 6; i++){
    color += hexes[Math.floor(Math.random() * 16)];
  }//end for loop
  return color;
}

$('.square').on('mouseenter', function () {
  $(this).css('background', genColor()); 
});

If you need further assistance, feel free to check out this working demo: https://jsfiddle.net/fb15L86u/

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 eliminate a vertical line from an HTML table?

I am looking to remove specific vertical lines from an HTML table. There are only 3 vertical lines in total, and I want to remove the first and third lines. Below is my code: <html> <head> <style type="text/css"> .table1{ background: ...

Error encountered while attempting to validate and add new entries

I am facing a challenge while attempting to insert a record into my mongodb database. Despite providing what seems to be the correct values, mongoose is flagging them as missing. Below is the Schema I am working with - var mongoose = require('mongoo ...

What is the best way to ensure a div occupies the full height within a grid layout?

https://i.sstatic.net/awwxE.png Looking at the image provided, I am seeking a way to make the top left image occupy the entire height just like the neighboring div in the first row of the grid. Is there a way to achieve this? The desired outcome should b ...

Struggling to populate a dropdown list with HTML, PHP, and MySQL

Here is the code snippet for creating a payment form: Everything seems to be working fine, but there is an issue with the supplier-ID dropdown. The dropdown is being created but it is not fetching data from the mysql table and no errors are being display ...

Error: Incompatibility - The variable is not functioning properly in node.js or express.js

Upon encountering the error message "TypeError: undefined is not a function," I called a callback with parameters null, array_reply, and threadResults. It appears that this section of code is problematic, but I am uncertain why. Your assistance in resol ...

Utilizing X-editable in an ASP MVC View: navigating the form POST action to the controller

I have been utilizing the X-Editable Plugin to collect user input and perform server submissions. However, I am encountering an error during submission. What adjustments should I make in order to ensure that the x-editable data functions properly with the ...

Trigger a specific directive instance through a function call when a key is pressed on the

Is it possible to trigger a specific directive instance's function when a global keyboard shortcut is pressed and it has the class "focused" based on ng-class? Below is some template code: home.html <body ng-controller="SampleController"> ...

Adjust the height of two floating divs to be the same when the window size is larger than a set width, then revert back to their original heights when the window width

I need help with the final piece of code to return the divs back to their original height after equalizing them. To view my current progress, click this link: http://jsfiddle.net/5fTXZ/1/ Below is the jQuery code I have implemented: // function to make ...

What's the best way to implement asynchronous state updating in React and Redux?

In my React incremental-style game, I have a setInterval function set up in App.ts: useEffect(() => { const loop = setInterval(() => { if (runStatus) { setTime(time + 1); } }, rate); return () => clearInterval(lo ...

Challenge with Context Api state not reflecting the latest changes

Hey there, I've got this function defined in AuthContext.js: let [authTokens, setAuthTokens] = useState(null) let [user, setUser] = useState(false) let [failedlogin, setFailedlogin] = useState(false) let loginUser = async (e) => { ...

Multiple calls being made to $on function within $rootScope

After my webservice completes data retrieval, I trigger $rootScope.$emit('driver-loader');. This signal is only sent from this particular location. In order to listen for 'driver-loaded', I have the following code snippet: var watchDri ...

What is the best way to preserve the state of a component in Angular?

I need to find a way to preserve the state of a data table within my Angular 7 & Typescript application. It's essentially like saving the state of a browser tab. When I navigate to another component and return to the one with the data table, how ...

Utilize JavaScript, jQuery, or Angular to incorporate identifications into <p> elements

I am working with a dynamically generated HTML document that contains several <p> tags with text inside. My goal is to be able to select a specific <p> tag when a user clicks on the text within it. However, I am restricted from adding ids to th ...

"Pushing elements into an array does not function properly within a promise

I'm having trouble with my code - the push method isn't working and it's not returning anything. import {nearbyUsers, getLatitude, getLongitude} from './helper' const users = [] nearbyUsers(session, getLatitude(), getLongitude()).t ...

Guide on making a dynamic circular spinning menu bar

I am struggling to create a circular spinning navigation bar using CSS3 and HTML. How can I achieve this effect? I have attached a picture from an old game that showcases the animation I am aiming for. When the active circle is selected, the corresponding ...

The React client is unable to establish a connection with the server socket

Recently diving into the world of socket-io and react, utilizing express for the backend. The socket.io-client version being used is 3.0.3, while the backend's socket-io package matches at 3.0.3 as well. Interestingly enough, the server handles connec ...

The problem arises from misinterpreting MIME types when serving SVG files, causing the resource to be seen as an image but transferred with

Having some issues targeting SVG images with CSS to use as backgrounds on certain elements. When I try to access the image directly here, it works perfectly fine. However, when using it in CSS, I encounter the following error: Resource interpreted as Imag ...

Deleting an HTML column that has a dynamic header name <th> can be achieved by following these steps

I have a script that can add a new column to an HTML table. When the user clicks on add group, the header will change to Group1, Group2, and so on. I am currently adding a function for delete group that can delete all the added columns. The issue now is th ...

I'm confused as to why the CSS Bottom property is causing the top edge of the div to align with the bottom of the document rather than the bottom edge

My challenge is to align an image slideshow on top of my footer, with the bottom edge of the slider touching the top edge of the footer. Despite using position: fixed and bottom: 0 properties, it appears that the positioning is off - aligning the top edge ...

JavaScript constructor functions may trigger ReSharper warnings for naming convention

When it comes to JavaScript coding, I personally prefer using PascalCase for constructor functions and camelCase for other functions. It seems like my ReSharper settings are aligned with this convention. However, when I write code like the following: func ...