How many 10 x 10 boxes fit into div? - javascript

This is a bit of a math problem mixes with some JavaScript, I have this adjustable div (https://imgur.com/a/Pec9Duq), when clicking on submit it will be filled entirely by 10 by 10 smaller div's.
But I don't quite know how to calculate how many row's of 10 by 10 div's will fit into the parent.
What I currently have is this code:
var w_items = Math.ceil(def_w / 10),
h_items = Math.ceil(def_h / 10);
That give's me back the rounded width and height of said parent, don't know how to calculate how many would fit thought, do I add them together or something?

Multiply the width and height of the parent div. You'll get its area.
Then, the area of a small div is 100 because of 10x10=100.
Then all you have to do is Math.floor(parentArea/smallDivArea) and you'll get the number of small divs that can fit into the big div.

If you floor (also known as integer division) the value instead of ceiling it, you will get the number of elements that can fit horizontally and vertically. The total count will be w_items * h_items.

Related

How do I get the number of items that will not fit inside the parent dynamically?

I currently have a draggable width container with some children.
Since its width is draggable once the width is small enough that say for example only 3 elements can fit.
Expected outputs are (0), (1), and (+4) (Number of elements that overflow + 1).
Other cases: Here only two elements fit, and 4 overflows.
The expected output is two circles with (0) and (+5).
I saw other posts where they use a fixed width and calculate the number of elements that can fit from that. However, in my use case, the width is varying and I need to get the number of elements that can fit/overflow dynamically. How can this be done using javascript and plain CSS?
var popupDiv = document.getElementsById("container")
let count = Math.round(window.getComputedStyle(popupDiv).width/widthOFElement)
I hope this help. here the widthOFElement is the width of round element. and you can add this in dragabble event listener.

Firefox sum of widths with jquery exceeds expected value

Firefox/Safari/Chrome all latest stable releases on macOS as of 12 May.
jQuery v3.1.0
I've a jquery script that dynamically resizes images (specifically, a container div which has an img element filling it 100%) inside a collection container div to give a masonry wall-like effect. The logic, heavily summarized, is that I calculate images at their preferred size for the current window width and add them up (including gutters) until they exceed that window width. I then subtract the last element and scale the remainder up to fit.
This works fine in Chrome and Safari. Firefox works on most rows but on occasion the last element gets bumped to the next row and throws the whole composition off. The culprit, on inspection, of the guilty rows appears to be that the sum of all the row elements exceeds the collection container by 1 pixel at most, never more. It's usually a fraction of a pixel. My hunch is that it's a rounding or decimal place issue; or an issue related to the floating point that I've seen come up in my research, like here.
Code:
Forgive me if I leave out anything pertinent here in the following code. I feel as though the relevance is in the calculations of the various elements widths through jquery (particularly, my scaleFactor result) so that should be enough and leaves this a bit more legible:
Calculations made in the script:
// Once it's been determined that a row has the required number of elements to fill it:
var windowwidth = $(window).width();
var gutter = 23;
var scaleFactor = (windowWidth - (sum of total gutters in row)) / (sum of total element widths in row);
// Looping through each element, resize them as such:
var w = $(this).width();
var h = $(this).height();
// Set new width and height
$(this).css({'width': (w * scaleFactor) + 'px'});
$(this).css({'height': (h * scaleFactor) + 'px'});
Result:
Chrome and Safari produce a row where the sum of all gutters and elements is consistently just under the window width by a fraction, giving visually perfect spacing, like so:
(23) + 936.094 + (23) + 415.859 + (23) // gives a sum of 1,420.953 for a window width of 1,421
Firefox, on inspecting a row where the last element was bumped off to the next row, gives the same example as follows:
(23) + 938.9 + (23) + 417.117 + (23) // gives a sum of 1,425.017 for a window width of 1,425
Additional Info:
I've given the img elements, their container divs and the content
container div box-sizing values of border-box in css to try and rule
out any styling discrepencies in the width values on each browser.
None had any padding or borders, regardless.
The content container div I mention here holds all the elements being arranged into rows. It is the width of the window less one gutter, which it uses as a margin. I've accounted for it in all calculations and am pretty confident I've done so appropriately as the sums would be out by a lot more than a fraction of a pixel if I've overlooked something more. I deliberately scale the elements to the window width, not the content container (its main purpose is to provide an opposing margin to the side each element has to give consistent and equal gutters around each element) but have tested with scaling to the content container and it gives the same outcome.
I've also confirmed that the width values I'm using here: (sum of
total element widths in row) is consistent across all browsers and
was sourced from jquery's width() function for each element. The
value for the window size on all browsers differs slightly - I
imagine due to scrollbar differences - but I can only assume it's
accurate. I've used other methods to get the window width without
scrollbars and they confirmed (to the best of my knowledge) that the
value being used is correct.
I've attempted rounding various parts and this confirmed my
presumption that it would not fix the problem when the sum of widths
exceeds the container by more than 0.5.
The measurements taken are done after all content is finished loading
and scrollbars are in place and accounted for, using the $( window
).on( "load", function() function.
Optimal Solution:
Ideally, I'm hoping I've overlooked an aspect of the calculation in the code, above, that can be adjusted to ensure that the same variables would produce the same results across browsers.
It's likely wishful thinking so my plan b would be an elegant means of compensating for this. Currently I could compare the window width with the sum total after the calculation and scale it back. Or I could forego precise gutters and aim to scale to the window width, less one pixel.
The problem with the first idea is that it seems like a poor design to patch a simple calculation that should work. It wastes lines of code and overhead and I avoid bloat as best as I can. The second solution annoys the perfectionist in me and could have long-term complications if I scale the project in a manner that's reliant on certain believed truths, such as even gutters throughout the layout.
Update:
I hadn't ruled out rounding various floats in the calculation just yet but was doing it mostly by guessing. My main lead was attempting to do on the widthBefore var as it was sometimes a float, whereas all the other vars in scaleFactor were integers. Round, as before, didn't work. To my surprise, floor didn't work. I thought it would leave minutely visible edge differences in spacing but it still left rows exceeding the window width. To my further surprise ceiling worked. I can't actually explain why Firefox needed me to round this value with ceiling to work but it's doing well with everything I throw at it so far. I still have to see what the repercussions are for gutter sizes now.
I can't fully explain the logic behind it. Likely, it would require someone knowing the subtler differences of maths calculations between the browsers, but rounding widthBefore by ceiling kept the same results in Chrome and Safari and, as per my question, provided the same results in Firefox.

How to calculate character width from font size.

I'm trying to calculate the number of characters that fits in one line of a div and trim off the rest although text-overflow is an option I rather calculate the length of the string that fits in it properly. Is the font-size of a character almost equal to it's width, if not how do you calculate it's width including the text spacing and the width of a white space.
P.S. - Before flagging this question, do know I've went through most of the questions and answers and none of them were satisfactory.
One way I would do it is to check if there's enough space left in the div. To do this, you would need to create an identical div and slowly remove one character from the cloned div until the original div is bigger or equal in width to the cloned div.
divClone.textContent = text
document.body.appendChild(divClone)
while(divClone.clientHeight > originalDiv.clientHeight) {
divClone.textContent = divClone.textContent.substring(0, divClone.textContent.length-1)
}
originalDiv.textContent = divClone.textContent
You can then delete the cloned div when it's done

Issue with creating thousands of div in javascript/jQuery

We need to create minute and second measurement units(displayed as bar) for 24 hours in HTML dynamically. We are using div for each unit.
For displaying units in second we need to create 86400 divs(24 * 60 * 60) and this is resulting in hanging the browser and not being able to create so many divs.
We used jquery html() method to create div as well as jsp pages to create so many divs. But both resulted in same way, browser gets hanged.
Is there any way to create 86400 divs using javascript (or any other way to be used in HTML)?
Code used:
var i;
for(i=0;i<86400;i++)
{
$('#innerDiv').append('<div class="unit">'+i+'sec</div>');
}
http://i.stack.imgur.com/s9wNs.png
one time append will increase the performance
var i;
var units = '';
for(i=0;i<86400;i++){
units +='<div class="unit">'+i+'sec</div>';
}
$('#innerDiv').append(units);
But its worth to consider the techniques like this techniques-smooth-infinite-scrolling-html5 if you have these much no: of elements to display
I'm not sure what your end goal is but maybe you could scale out to showing only minutes or half hours depending on the scale of the number of hours. As a ruler a division of seconds seems excessive if a large timeframe of 24 hours is selected. I recently made a ruler using a table just to show the scale and that worked well. Are you interacting with all those divs via script after drawing them as this seems like a more likely reason for the crash especially if inserting static include crashes the browser as well which doesn't sound right. You might need to say what some of those post drawing tasks are, theres alwaysmore than one way to do things.
Anyway, if you know the width the seconds will be you could create a background image with a 1 pixel left or right border and make it a repeating background on a larger div which represents a minute for instance (or the background image could be 5 minutes in a div of an hour). Each div could have a child element that displays the larger divs scale value (1, 2, 3 etc or 5, 10 15 etc as long as you have a scale key). The background image shows the seconds but you only create divs for the larger measurements of the scale with numbers. I can share some code if that might be a possble avenue for you.

How to determine how many CSS3 columns are actually being displayed (vs. the specified column-count)?

I have a list of tags that are in a box that I've specified as having multiple columns:
#tags {
-webkit-columns: 140px 5;
}
Result:
The content of this list is dynamically generated.
When I resize the browser window, the number of columns collapses. e.g.:
Using jQuery / JS / CSS / etc., how can I determine how many columns are being displayed at any given time?
Unless you specified all column width-related properties browsers will try to fit whole number of columns in content area (between left and right padding of element). So (contentWidth + columnGap)/(columnWidth + columnGap) rounded down will give you result.
Note that right padding may be set so high that whole column will be able to fit there - you may need to adjust computations.
You can also directly get size of column if you have an element with 100% width inside columns text.
You can get the value like this:
$('#tags').css('-webkit-column-count');
Try alerting this:
alert($('#tags').css('-webkit-column-count'));
Similar to Alexei's answer, I figured out a solution to get the column count:
var $tags = $("#tags"),
column_width = $tags.children(':first').width(),
container_width = $tags.width(),
column_count = Math.floor(container_width / column_width); // in my case, sum of column gaps is less than the width of a column, so I can round down.

Categories