I’m trying to code the following JS in coffeescript:
x = 0;
if(node.offsetParent) {
do {
x += node.offsetLeft;
} while(node = node.offsetParent);
}
Here’s what i have so far, but the node seems to come back null
if node.offsetParent
loop
x += node.offsetLeft
break if typeof (node = node.offsetParent) == "undefined"
x
The problem is simply that when a DOM element
nodehas no offset parent,node.offsetParentisnull, notundefined. Andtypeof nullis'object', not'undefined'.Why not take the same approach as the original JS loop, which simply checked
node.offsetParentfor falsy-ness? Then your code might look something like:I’d also like to point out that while CoffeeScript has no
do..whilesyntax, you can simply use awhileloop in this case, making yourifsuperfluous: