My grid elements are multiplying by 10 and I can't find the reason
When the user uses the slider, the currentSize variable changes successfully (I have been console.logging like crazy) but then when the grid reloads, shit hits the fan and It does generate but it multiplies by 10, that is, if the user picks 1 as their grid size, they 10 squares instead of just 1. If they pick 2, instead of a 2X2 grid (4 squares) they get 20. The thing is, the createGrid function is working correctly. When you call it by itself, it works no problem. This just happens when the user slides.
Here's the link to the codepen. Thanks in advance (btw the grid elements borders are just decorative, so we can see stuff is working properly)
https://codepen.io/norwyx/pen/MWRmzza
3 Replies
you're being bitten by javascript's bullshit
const total = (numberPerRow * numberPerRow) + numberPerRow;
this is where the SYMPTOM of the bug happens
the code is fine, you just don't have any jsdocs and you let a string slip in
this is the relevant code
e.target.value
<-- this is a string
const total = (numberPerRow * numberPerRow) + numberPerRow;
<-- when it gets here, it's still a string
('1' * '1') + '1'
= '11'
if the value is 16, then it becomes this: ('16' * '16') + '16'
that + '1'
forces everything to be a string
how do you fix this?
well, there's 2 things you can do
0- use jsdoc so you don't suffer this bug ever again
1- convert the value to an integer
2- change the math
why are you multiplying and then adding the value itself to it?
you just need to loop from 0 to total
, and total is just numberPerRow * numberPerRow
for (let i = 1; i < total; i++)
<-- and then you can change the <
for <=
if it doesn't loop enough times
or start with 0thanks bro
you're welcome