What is the best way to populate a div with multiple other div elements?

My current project involves creating a sketchpad using jQuery for an Odin Project assignment. However, I have encountered an issue with filling the canvas (wrapper div) with pixels (pixel divs). The canvas does not populate correctly. Here is the link to my code on jfiddle:

http://jsfiddle.net/c3sq2jmb/2/

Below is the code snippet:

HTML:

<body>
    <div class="wrapper">

    </div>
</body>

CSS:

.wrapper {
    height: 300px;
    width: 300px;
}

.pixel {
    display: inline-block;
    background-color: black;
    margin:0;
    vertical-align: top;
    float:left;
}

JS/jQuery:

$(document).ready(function(){
    createGrid(16);
});


function createGrid(number) {
    for(var i = 0;i <= number*number;i++) {
        $('.wrapper').append('<div class="pixel"></div>'); //adds pixels based on user command, default 16
    }
    $('.pixel').height($('.wrapper').height()/number); 
    $('.pixel').width($('.wrapper').width()/number);
}

$('.pixel').hover(
    function() {
        $(this).css('background-color', 'white');
    }
);

Furthermore, there is a secondary question related to the hover function behavior discrepancy between jfiddle and Chrome browser. On jfiddle, the hover effect works as intended, but it fails in Chrome. Any insights into why this might be happening?

PS: Although my project is still work-in-progress, I've reached a roadblock in resolving this issue.

Answer №1

There's a small bug in your code where you have an off by one error.

for(var i = 0;i <= number*number;i++) {

The correct way to write it is:

for(var i = 0;i < number*number;i++) {

Apart from that, everything else appears to be functioning fine.

Answer №2

When attempting to render 300px/16, you will end up with 18.75px (not a whole pixel value). This can cause the browser to struggle in rendering properly and result in black fragments appearing when hovering over the element. However, if you use a 15 grid instead, it works seamlessly (300/15 = 20px box). To address any additional issues with a black box at the very end, consider using the following code snippet:

for(var i = 0;i < number*number;i++)

Check out the updated Fiddle for more details.

Answer №3

Check out the functional DEMO:

The loop and pixel size assignment have been fixed.

for (var i = 0; i < number * number; i++) {
  $('.wrapper').append('<div class="pixel"></div>');
}
...
$('.pixel').each(function () {
    $(this).height(height);
    $(this).width(width);
});

To resolve the Chrome issue, make sure to place your method inside a document ready block:

$(document).ready(function () {
  createGrid(16);

  $('.pixel').hover( function() {
    $(this).css('background-color', 'white');
  });
});

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

Transform strings in a table into integers within a specified scope

My World.json file is quite large and contains extensive data on countries worldwide. I've been utilizing a list to display this data in a table format, with the intention of sorting all values accordingly. However, I have encountered an issue - all m ...

What is the best way to send form data to MongoDB using React?

I am seeking guidance on how to pass the values of form inputs to my MongoDB database. I am unsure of the process and need assistance. From what I understand, in the post request within my express route where a new Bounty is instantiated, I believe I need ...

Tips for designing a unique style attribute for your Vue.js component

My goal is to utilize Vue.js without the need for a build step, but I've encountered an issue with its lack of a style property. To tackle this problem, I came up with the idea of creating a custom "style" property on my Vue component instance and dy ...

The Electron BrowserWindow turns dark post execution of the .show() method

Revision: After some tinkering, I discovered that the issue was related to the order in which I created the windows. Previously, my code looked like this: app.whenReady().then(() => { createWindow(); spawnLoadingBlockWindow(); spawnGenerati ...

Plugin for creating a navigation bar with a jQuery and Outlook-inspired style

Our team is considering transitioning our asp.net forms application to MVC. Currently, we utilize outlook-style navigation with ASP controls such as listview and accordion, using code referenced here. Are there any jQuery/CSS controls available for MVC t ...

Chrome is having trouble setting the cookie with the Set-Cookie header

I am making an AJAX call to another service's API, expecting to receive a cookie that will be stored in my browser for future API calls. Unfortunately, even though the response headers contain a 'Set-Cookie' header, the cookie is not being s ...

Exploring the versatility of combining CSS classes with MUI 5 SX prop

Is there a way to use multiple CSS classes with the MUI 5 SX prop? I've defined a base class for my Box components and now I want to add a second class specifically for styling the text inside the Box. When I try to apply both classes like sx={styles. ...

Multiple instances of the identical 'Angular application' displayed simultaneously on the webpage

We've created a unique Angular 1.0 application that we aim to embed as a 'widget' within another website built with classic asp.net. During the development phase of our angular app, we take advantage of a range of gulp tools for tasks such ...

Is there a way to alter a class using ng-class only when the form is deemed valid?

I am trying to implement a feature where an input field shows as required, but once the user enters text, it indicates that the input is valid by changing the border color from red to green. I am facing an issue with this line of code always returning fal ...

Learning how to invoke a JavaScript function from a Ruby on Rails layout

In the file app/views/download.js.erb, I have defined a javascript function named timeout(). This function continuously polls a specific location on the server to check if a file is ready for download. I am currently running this function as a background ...

Adjusting the size and positioning of an image with CSS

Here is my situation: I am working with an image that is 1900 x 1600 pixels in size. I also have a div that is sized at 200 x 150 pixels. To adjust the image size, I used the following CSS: max-width:300px; max-height:300px; The height will be adjuste ...

Can you modify a WordPress/WooCommerce title written in uppercase to display in proper capitalization?

My current project is centered around WordPress and utilizes WooCommerce as its e-commerce platform. I recently migrated products from an old site where the product titles were written in uppercase. At the moment, my HTML code for the product titles looks ...

Using the identical code, Wicked PDF generates distinct reports on separate computers

While utilizing Ruby on Rails to render a PDF using WickedPDF and sending it via email, I encountered an unexpected issue. The same code is present on two separate computers, both with up-to-date versions synced from GitHub. However, the generated PDF repo ...

Sliding in the wrong direction on Bootstrap 5.2 carousel

I'm currently working on a carousel project. However, I encountered an issue where the images slide down initially and then jump up to the correct level as depicted in the image below. I've tried adjusting the height, width, and auto settings to ...

ngClass causing styling issue when applying styles

When I use class names like error and info, the CSS works fine. For example, in this Angular app (latest version) here: https://stackblitz.com/edit/github-i4uqtt-zrz3jb. However, when I try to rename the CSS classes and add more styles, like in the examp ...

Can a div's style be modified without an id or class attribute using JavaScript or jQuery?

Is it possible to change the style of a div that doesn't have an id or class assigned to it? I need some assistance with this. Here is the div that needs styling: <div style="display:inline-block"> I would like the end result to look somethin ...

What are some ways to create a responsive image design?

Currently, I am using the code below to enlarge an image when clicked on. I have attempted using media queries in CSS... I have also added another class in #modalPopupHtml# to adjust the size of the large image: .imgsize{ height: 600px; width: 800px; ...

Tips for adapting my custom input component for compatibility with vee-validate?

I recently developed an input component for my Vue project and integrated it within my forms. My aim is to implement vee-validate for validating the inputs. Initially, I attempted to validate my component like any regular input field. However, upon encoun ...

jQuery UI Datepicker extending beyond its bounds

My Datepicker is expanding and filling the entire screen. What could be causing this issue? Here is my code: Additionally, how can I change the date format in jQuery to appear as dd-mm-yyyy? https://i.stack.imgur.com/IQzVV.png HTML: <!DOCTYPE html&g ...

Sharing an array with a child component using the @Input decorator

I am attempting to send an array to a child component. The array is created within the subscribe method of the onInit lifecycle hook in the parent component. Parent component: import { Component, OnInit } from '@angular/core'; @Component({ s ...