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

Change all lowercase characters to uppercase in the font file

: I recently created a .ttf font file, but unfortunately only included capital characters. Is there a tool or simple method I could use to automatically create lowercase versions of each letter? For instance, when typing "hello" the font should display ...

Fetching weather data from the Darksky.com API in JSON format

My goal is to retrieve weather data in JSON format from the Darksky.com API. To do this, I first successfully obtained my latitude and longitude using the freegoip.com API. However, the Darksky API requires both longitude and latitude before it can provid ...

Is it possible in PHP to automatically retrieve all data posted through POST and uncheck multiple checkboxes simultaneously?

Hey everyone, I could really use some assistance. I'm attempting to utilize this code to dynamically retrieve variables and values from a form. However, the form contains numerous checkboxes that may or may not be checked. I'm looking for a way ...

Top choice for PHP integration of autocomplete feature for addresses including streets, cities, and countries

I'm currently using jQuery UI Autocomplete to populate the street, city, and country fields. I am looking for ways to program in PHP so that when the term parameter is passed to the server, it only looks up the street name and not the city and country ...

"Encountering difficulties while setting up an Angular project

I am currently working on setting up an Angular project from scratch. Here are the steps I have taken so far: First, I installed Node.js Then, I proceeded to install Angular CLI using the command: npm install -g @angular/cli@latest The versions of the ...

What is the process for eliminating the hover effect on a Bootstrap button?

I have customized a Bootstrap button in my stylesheet to make it dark, but it still has a hover effect from Bootstrap that I want to remove. How can I get rid of this hover effect? Take a look at the code snippet below for reference: .btn-dark { min-w ...

Looking to transfer JSON data between JavaScript and Java code

I am dealing with a JSON string within my JavaScript code and I want to pass this information to a Java class. Can I simply use a regular Java class for this task or is it necessary to implement a servlet? Furthermore, I am curious about the process of pa ...

Creating two columns with separate scrollbars in Responsive Bootstrap is a useful feature for organizing content in a visually

Is there a way to create 2 columns with scrollbars using Bootstrap when a button is clicked? Here's what I'm trying to achieve: My webpage consists of a row-fluid div that contains the main-column div with main-content and extra-content. There&a ...

The app constantly requests permission for geolocation services

While experimenting with the geolocation API, I encountered an issue where my page kept repeatedly asking for permission upon refresh. To work around this problem, I attempted to save my coordinate data to local storage but encountered difficulties in ma ...

Tips on updating service variable values dynamically

I need to update a date value that is shared across all controllers in my website dynamically. The goal is to have a common date displayed throughout the site by updating it from any controller and having the new value reflected on all controllers. Can yo ...

Creating a straightforward game using node.js, socket.io, and jquery, where users can take turns participating

I am currently working on a game using node.js, socket.io, and jquery. The game involves two users logging in from different locations and browsers. When the first user logs in to play, they receive a message saying "Your Turn" and have 30 seconds to make ...

Is it advisable to incorporate multiple images onto a single canvas?

What is the best approach to handling multiple images in HTML5? Is it preferable to create a separate canvas tag for each image or is it equally effective to have multiple images in one canvas, and how would I go about doing that? Here is the code I have ...

Tips for aligning three cards in a row using Bootstrap-5

In my Django template for loop, I am trying to display the first three cards from the database on the same line. Currently, only two of them are staying on the same line and I want all three cards to be aligned horizontally. <div class="row"&g ...

Conceal the message "Table does not contain any data" if data exists in the table

This table is populated with data retrieved via JSON. Here is the structure: <table id="tblClaimSearch" class="display responsive nowrap" cellspacing="0" width="100%"> <thead> <tr> <th><input type="checkbox" ...

Arrange a line of images in the center

I've been working on aligning images in a row and centering them using flex, but I'm having trouble figuring it out. I managed to center all the images with flex and justify-content center, but setting flex-direction: row on the container doesn&a ...

Using HTML's select option to submit a request for data retrieval from PHP using PDO with MySql database

I am having an issue with fetching data from MySQL based on Select Month and Year in HTML Select Option. When I submit the view, the table should be filtered accordingly. Otherwise, all data should be displayed. However, my code is generating an error. No ...

Clicking on a href link inside a scrollable div-container causes it to malfunction, causing the page to jump

I have a draggable div container that contains dynamically generated content. In order to display this container, I use the following code: $( function() { $( "#dialog-message" ).dialog({ modal: true, height: 400, buttons: { Fertig: functi ...

Is there a way to export a variable that has been declared within a function component in React Js?

I am currently developing a React app and I need to export the RoomPricelist1 & FacilityPricelist1 variables. I have assigned values to these variables within a function component but when I try to import them into another function component, they are sh ...

Warning: DataTables Alert

My goal is to showcase a table in asp.net by following this example. However, I'm encountering an error that reads: DataTables warning: table id=datalistTable - Requested unknown parameter '1' for row 0. For more information about this ...

The Vue.js application is experiencing issues with the v-for functionality

I am working on a Vue.js application where I am fetching a list using ajax: $.ajax({ method: 'POST', dataType: 'json', url: this.base_info.url + 'getavailability?token=' + this.token, data: this.search_inf ...