2

I am trying to write a code that set CSS for some dynamic elements added on click on a link.

As per the example code in CoffeeScript tutorial it should be working with the following code.

temp = temp+1
$ '.box_'+temp
.css 'background', 'white'

Here temp is a variable integer. I tried with static values like

$ '.box_1'
.css 'background', 'white'

but it returns something like this with .css not a function error

$('.box_1'.css('left', 100));
4
  • 3
    Strange. My compiler compiles your examples to $('.box_' + temp).css('background', 'white'); and $('.box_1').css('background', 'white');. (version 1.8.0)
    – Amadan
    Commented Mar 31, 2015 at 5:11
  • 2
    What's wrong with throwing in some parentheses to clarify your intent? $(".box_#{temp}").css('background', 'white') or $(".box_#{temp}").css 'background', 'white' are perfectly good CoffeeScript. Code is supposed to be readable, if you have to spend more than a second parsing the syntax then the code is effectively broken. Commented Mar 31, 2015 at 5:31
  • its not working even with static value .box_1
    – Vikram
    Commented Mar 31, 2015 at 5:36
  • The official CoffeeScript disagrees with you. The only way I've been able to get your results is to put it all on one line. Commented Mar 31, 2015 at 6:21

1 Answer 1

5

Just add parens to remove ambiguity and save yourself the headache.

temp = temp+1
$('.box_'+temp)
.css('background', 'white')

Sexy function calls are optional syntactic sugar, not required. You should not be using language features if doing so makes your code less clear for humans or machines (or in this case, both!)

Not the answer you're looking for? Browse other questions tagged or ask your own question.