JQuery isn't functioning properly on dynamically generated divs from JavaScript

I'm currently tackling an assignment as part of my learning journey with The Odin Project. You can check it out here:

Despite creating the divs using JavaScript or jQuery as specified in the project requirements, I am unable to get jQuery's .hover function to work on these divs.

Here is a snippet of the JavaScript code I used:


function createGrid(resolution) {
    var wr = document.createElement("div");
    wr.setAttribute("id", "wrapper");
    document.body.appendChild(wr);
    for (x = 0; x < resolution; x++) {
        for (i = 0; i < resolution; i++) {
            var pix = document.createElement("div");
            pix.setAttribute("class", "pixel"); 
            wr.appendChild(pix);
        }
        var clr = document.createElement("div");
        clr.setAttribute("class", "clearLeft"); 
        wr.appendChild(clr);
    }
}

function getRes() {
    var resolution = prompt("Enter your desired grid resolution. Number must be between 3 and 64");
    if (resolution > 64 || resolution < 3) {
        alert("This number is beyond the acceptable range. Pick a number between 3 and 64");
        getRes();
    }   
    createGrid(resolution);
}

// While no errors are showing up in the console, the hover effect is not working after adding the script below
$(document).ready(function() {   
    $(".pixel").hover(function() {   
        $(this).css("background-color","black");
    }, function(){
        $(this).css("background-color", "black");
    });
});

Answer №1

If you want to add an event handler right after creating your function, you can modify it like this:

function createGrid(resolution) {
  var wr = document.createElement("div");
  wr.setAttribute("id", "wrapper");
  document.body.appendChild(wr);
  for (x = 0; x<resolution; x++)
    {
      for (i = 0; i<resolution; i++)
      {
        var pix = document.createElement("div");
        pix.setAttribute("class", "pixel"); 
        $(pix).hover(function(){   
           $(this).css("background-color","black");
        }, function(){
           $(this).css("background-color", "black");
        });
        wr.appendChild(pix);
      };
  var clr = document.createElement("div");
  clr.setAttribute("class", "clearLeft"); 
  wr.appendChild(clr);
 };
};

Another approach is using event delegation by attaching the event handler to a static parent element when working with dynamically created elements using on. Here's how you can do it:

$(document).on("mouseenter",".pixel",function (e) {

});
$(document).on("mouseleave",".pixel",function (e) {

});

With this method, you'll need to bind the handlers for mouseenter and mouseleave separately.

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

Guide to dynamically updating a textarea in vue.js by incorporating data from several inputs

Is there a way to update a textarea based on multiple inputs using jQuery and vue.js? I have successfully implemented the jQuery part with line breaks, but when I try to display the value of the textarea elsewhere using vue.js, it doesn't seem to work ...

primary and secondary colors within the Material UI design scheme

Is there a way to apply different colors for Cards and Papers in the Material UI Theme that are compatible with both light and dark modes? In my app, I have a list of Cards placed on top of a Paper background. Currently, the default color for both the Pap ...

Json node tabbing

[ { "idn" : "liquido", "categoria": "Aromatizante Ambiental Liquido", "productos": [ { "nombre": "Canela" }, { "nombre": "Chanel" }, { "nombre": "Citrus" }, ...

CSS printing displays a blank bar in white color

Attempting to generate a ticket with the dimensions of 203mm x 82mm using HTML and CSS through Python (including cgi, jinja2, weasyprint). The template will be converted into a PDF for users to download via a button on the website. The HTML Body: <body ...

The code is running just fine when tested locally, but it seems to encounter an issue when accessed remotely, yielding

Currently, I am in the process of developing a dual twin setup using a Raspberry Pi. The goal is to simulate a continuous transmission of body temperature data, which is then sent to a server that stores the information in a MongoDB database. Everything fu ...

Running Controllers from Other Controllers in AngularJS: A Guide

Switching from a jquery mindset to Angular can be challenging for beginners. After reading various tutorials and guides, I am attempting to enhance my skills by developing a customizable dashboard application. Here is the HTML I have so far: <div ...

Jquery issue: Lightbox unexpectedly closing by itself :(

Help needed: My light box is closing automatically within seconds. $(document).ready(function(){ $('.lightbox').click(function(){ $('.backdrop, .box').animate({'opacity':'.50'}, 300, 'linear'); ...

Transform your dictionary into an interactive HTML table that allows users to search through the results with ease

I have a university project where I need to exchange data via JSON using a Python script and a server, and then display it in a browser with an add and search function. The information being added includes student names, surnames, and ages. I must apologiz ...

What is the best way to extend an inline-block element to cover the entire text line?

Let's talk about the scenario: https://i.stack.imgur.com/we05U.png In the image, there is a container (displayed as a div) with only one child - a span element. The goal is to introduce a second child that occupies the entire red space depicted in t ...

What is the best way to update and add data with just one click using jQuery?

Trying to dynamically add text to textboxes by clicking an "add" button. The code allows for adding/removing textboxes that save values to and delete from a database. Upon page load, a function called showitem creates textboxes dynamically and populates th ...

React Native: Enhance the background with a vibrant stripe of color

I am trying to incorporate a strip of grey in the middle of my white background, but I am encountering an issue where I am unable to input any text inside it. Below is the code snippet I am working with: container: { flex: 1, justifyContent: "cent ...

Does the resolve function within a Promise executor support async operations?

I'm trying to wrap my head around the following code: function myPromiseFunc() { return new Promise((resolve) => { resolve(Promise.resolve(123)); }); } We all know that the Promise.resolve method immediately resolves a Promise with a plain ...

When the state changes in React, the useSelector hook does not provide real-time updates

Currently, I am in the process of implementing a search feature using React and Redux Thunk. The main requirement for this search functionality is to fetch data from an API by calling a thunk action and updating the state accordingly for display on the UI. ...

Confirming the presence of an image using jQuery without enforcing it as mandatory

Situation: In my setup, I maintain a database that holds details about various items. Currently, I utilize a dynamic form to retrieve and exhibit the existing information on any item stored in the database. Any modifications made on the form are promptly ...

Using ES6, when utilizing array map in ReactJS, the function does not produce a return value

One challenge I'm facing involves mapping an array to find a specific string value. Unfortunately, despite my efforts, the map function is not returning anything as expected. class Application extends React.Component { constructor(){ super(); ...

Steps to configure npm start for an electron application using "babel-node --presets es2015,stage-3"

I've been experimenting with getting my npm start to work properly for electron. Typically, you would start a non-distributed app with electron . or ./node_modules/.bin/electron .. However, due to my use of NodeJS v8.4.0 and ES6/7 syntax, my npm start ...

The conditional statement within an AngularJS object is reliant on the selected option within an HTML dropdown menu

I am looking to apply an if condition in an object to capture specific values from two HTML select options. The Angular framework will then post these values to the database based on the user's selection. HTML <tr> <td>En ...

Tips for resolving the issue of 'no serverless pages built' during deployment of a Next.js application on Vercel

Recently, I've been encountering the same two errors while trying to deploy my NextJs app: // and will just error later on Error: No serverless pages were built. You can learn more about this error here I'm stuck and unsure of how to resolve bo ...

Newbie inquiries regarding the process of migrating a CRUD application to PhalconPHP

I have recently delved into using PhalconPHP 1.3.1 for an application related to my master's thesis. While it is still a work in progress, I am currently focusing on implementing CRUD functionality and refining the user interface. This endeavor marks ...

Dynamically remove values from other fields in a React Formik form based on checkbox conditions

Currently, I am utilizing react-formik for my form implementation. I have encountered an issue with checkbox-based conditions where the checked status of a checkbox determines whether two hidden fields are displayed or hidden. If the user checks the checkb ...