-2

I have this JS to get the widths of a bunch of sibling elements and add those widths to an array.

var nav = document.querySelector('.js-primary-nav');

var childrenWidths = [];

for(var i=0; i<nav.childElementCount; i++){
    childrenWidths.push(nav.children[i].offsetWidth);
}

Now I want to cycle through these widths, adding them up until the total is greater than X (which will be the container width). I then want to get the positions of the values up until the one which tipped the total over into larger than X so I can add those values to one pile and the others to another.

How do I cycle through the values, adding and then comparing the total to a number?

Thanks

  • Use a `for` loop to iterate, use `+` operator to sum, use `>` operator to check if it's larger. – Oriol Jan 29 '15 at 16:13
  • the same way you looped through the nav. Instead of doing 2 loops I would have a running count as you add them to childrensWidths – scrappedcola Jan 29 '15 at 16:13
  • you seem to be familiar with `for` loops. Is there something specific that makes it diffcult for you to loop through elements of an array? – Igor Jan 29 '15 at 16:13
  • Start from [here](http://stackoverflow.com/questions/9329446/for-each-over-an-array-in-javascript) – hindmost Jan 29 '15 at 16:13

1 Answers1

0

You need to define X, but it's a simple loop.

Iterate the nodeList, add the current offsetWidth to the variable tracking, make sure to define the max so you can pass the condition.

When current > max, run whatever code you need to and escape the loop.

var max = [number];
var current = 0;
[].forEach.call(document.querySelector('.js-primary-nav'), function(x) {
    current += x.offsetWidth;
    if (current >= max) {
        //do something
        return;
    }
});
Sterling Archer
  • 22,070
  • 18
  • 81
  • 118
  • Thanks, but that gives this error in the console: `Uncaught TypeError: Cannot read property 'forEach' of undefined`. – Andy Lobban Jan 29 '15 at 16:32
  • 1
    You probably meant `[].forEach` or `Array.prototype.forEach` or `Object.getPrototypeOf([]).forEach` or `[].__proto__.forEach`. But not `[].prototype.forEach`. – Oriol Jan 29 '15 at 16:35