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

Searching for matching strings in jQuery and eliminating the parent div element

Here's an HTML snippet: <div id="keywords"> <div id="container0"> <span id="term010"> this</span> <span id="term111"> is</span> <span id="term212"> a</span> <span ...

React - warning - Avoid using <Link> outside of a <Router> context

Warning: Invariant failed: It is not recommended to use <Link> outside of a <Router> Encountering this while attempting to write a test for a component where test("renders post list div ", () => { const posts = [ { created: ...

Is it possible to verify the versions of node and npm prior to running an npm install command?

To ensure only specific versions of node and npm are used before a user can run the npm install command on my module, I need to set certain criteria. According to NPM documentation, I can use the engine attribute for this purpose: "engines": { "nod ...

The modal remains visible

Has anyone encountered a problem with hiding a Bootstrap modal based on form validation in JavaScript? I'm facing an issue where the submit function is not executed when I click the button. I've attempted using onsubmit=validateForm(), but it doe ...

Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column: receiptsByDate: function(){ let byDate = _.groupBy(t ...

Can one initiate a server within Zapier Code?

Is there a way to send an HTTP CODE = 200 with a response body of 'OK' when receiving a notification on Zapier? I attempted to use the following code snippet in Zapier: var http = require('http'); const server = http.createServer((r ...

Can we achieve live map updates in real time using Google API with Node.js technology?

Can Google Maps API in conjunction with Node.js provide truly real-time updates on a map without any callback limits, or does Google enforce restrictions such as a 5 second or 30 second time frame? Node.js is known for its ability to handle almost real-ti ...

Problem with the transform attribute in CSS

Having trouble rotating a div within another div. I tried using the transform property but it's not working as expected. I heard about another method which involves using :before pseudo-element, but I'm not sure what's wrong with that either ...

Synchronize custom directive controller data with data from a factory

As a newcomer to angularjs, I stumbled upon this example that I found somewhere and it works perfectly well. However, I am puzzled by how the data within the customized directive controller remains synchronized with the factory data. Here is the snippet of ...

"Duplicate content issue with ng-transclude causing element to render twice

Why is the transcluded directive displaying Name inside directive = Frank twice? I believed I had a good grasp on transclusion, but this specific scenario has left me puzzled. Check out this fiddle for more details <div ng-app="myApp" ng-controller=" ...

What is the best way to find a partial string match within an array of objects when using Jest?

I am currently utilizing the following versions: Node.js: 9.8.0 Jest: 22.4.2 A function called myFunction is returning an array structured like this: [ ... { id: 00000000, path: "www.someUrl.com/some/path/to" } ... ] I ...

Nested click jQuery with draggable elements

After taking advice from @amphetamachine in this thread, I was able to successfully manage nested clicks using jQuery. However, the drag feature that was previously functioning perfectly has now stopped working since I implemented the delegates. The main ...

Different types of video formats used for html5 video players

Looking for some guidance here. I'm currently in the process of developing a website that allows users to upload their own videos. For the video player, I've opted for the HTML5 player by . My main concern is ensuring that the HTML5 player can on ...

Ways to display a JSON object in CSV format

Is there a way to export a JSON object to a CSV file, where the sub-fields contain arrays of objects? I am unsure how to properly represent this embedded data in the CSV format. ...

Guide on Organizing Information in Next.js

I have an online store and I am looking to organize my data by categories. Initially, I tried using APIs for this purpose but it ended up putting a strain on my server. So now, I am attempting to use Redux to store the data and filter it from there. Howeve ...

Incorporating additional value attributes without replacing the existing ones

Is there a way to add a value attribute through jQuery without removing the old attribute, similar to how addClass works? I have 7 input fields that are being typed in, and I need to combine them into one word and pass it to another input field. When I try ...

Issues arising from the combination of two variable values

I'm facing some issues trying to combine two variables and insert them into an ajax post URL. Unfortunately, I keep receiving error messages. Let me share what I have attempted so far: var photoId = 227; var jobId = 334; $.ajax({ type: "POST" ...

Struggling to resolve problem with MoveTargetOutOfBoundsException or encountering difficulty scrolling into view in Firefox

Despite trying numerous options, I've hit a roadblock in Firefox where my code can't seem to locate an element that is clearly visible on the screen. Below is a snippet of my code including variable declarations: ''' *** Variables ...

Display hyperlinks upon hovering over text

In the sign-up form, there are options for two different types of users: teachers and students. When the sign-up option is selected, a drop-down menu with choices for teacher and student will appear. However, I would like it to function more like other w ...

What is the best way to choose a specific section of a string using JQuery?

When utilizing the .html() function to retrieve html code, I encounter a need to extract a specific segment of the string. var newImgAdr = $(this).html(); The variable newImgAdr currently consists of: <img class="thumbnail-holder image-responsive cen ...