I’m trying to get a list of values. Basically I’m trying to calculate columns widths for photoshop template, with JS. It looks like this : one 15px gutter, one 52px column, one 15px gutter, one 15px gutter, one 53px column, one 15 px gutter. Basically I need to add 36 values to my initial value, and print every step of that calculation.
So my loop consists of 6 elements. Here is what I did :
col1 = 52;
col2 = 53;
gutter = 15;
result = 145;
for (i = 0; i <= 6; i++) {
result = result + gutter;
document.getElementById("result").innerHTML = result.toString();
result = result + col1;
document.getElementById("result").innerHTML = result.toString();
result = result + gutter;
document.getElementById("result").innerHTML = result.toString();
result = result + gutter;
document.getElementById("result").innerHTML = result.toString();
result = result + col2;
document.getElementById("result").innerHTML = result.toString();
result = result + gutter;
document.getElementById("result").innerHTML = result.toString();
}
If I replace innerHTML with a console.log, it will work perfectly. But I think it’s better if it works with innerhtml. The problem is, with that function, the div#result will only show the last value of result variable. And I want to see every step..
By the way I think my function could be written better. There’s a lot of repetition in it
EDIT : here is the updated code thanks to gillesc, as you can see its quite ugly but it works
col1 = 52;
col2 = 53;
gutter = 15;
result = 145;
space = "<br/>";
for (i = 0; i < 6; i++) {
result += gutter;
document.getElementById("result").innerHTML += result.toString() + space;
result += col1;
document.getElementById("result").innerHTML += result.toString() + space;
result += gutter;
document.getElementById("result").innerHTML += result.toString() + space;
result += gutter;
document.getElementById("result").innerHTML += result.toString() + space;
result += col2;
document.getElementById("result").innerHTML += result.toString() + space;
result += gutter;
document.getElementById("result").innerHTML += result.toString() + space;
}
2
Answers
Here is a more elegant way. Build up an array and use
join()
to create your spaced string. UpdatinginnerHTML
only once.+=
to append,=
to replace. So stop replacing theinnerHTML
and append to it.+=
works for number too soresult = result + gutter;
can simply beresult += gutter
.Added
var
everywhere as well to avoid those variables being on the global scope.JS Fiddle
You are reassigning the
innerHTML
element every time. Stop doingdocument.getElementById("result").innerHTML = result.toString();
anddocument.getElementById("result").innerHTML += result.toString();
.Small notes:
document.getElementById('result');
once before the loop to improve performance.result.toString()
, JS is smart enough to convert it when appending to a string.I would suggest doing: