1

Using jQuery and coffeescript, I want to update a html element when user presses enter. My code looks like this:

$ ->
  $('p span').live 'keypress', (e) ->      
    if e.keyCode == 13        
      $('div.sidebar-nav ul li a.active').html $(this).attr 'value'

Coffeescript compiles without any errors, but the code is not working. For some reason, if I add change the code to following it works:

$ ->
  $('p span').live 'keypress', (e) ->      
    if e.keyCode == 13
      alert 'some string'
      $('.sidebar-nav a.active').html $(this).attr 'value'

I spend last few hours trying to solve this and still nothing. Any help would be deeply appreciated.

14
  • 1
    Holy crap what is $ -> in coffeescript? Commented Jun 2, 2012 at 22:03
  • 2
    @gdoron: Like in JavaScript, $ is just a function. -> introduces an anonymous function. CoffeeScript also adds calling functions without parentheses. Put the pieces together, and you get $(function() { /* ... */ }); Commented Jun 2, 2012 at 22:04
  • 1
    @gdoron: It doesn't remove the ability to use parentheses; it just makes them optional. If you're asking about whether 'value' is another argument, it's not, because there's no comma. Commented Jun 2, 2012 at 22:08
  • 1
    @icktoofay. Thanks for this one minute tutorial, Now I'm sure I don't want to use it. YACK! Commented Jun 2, 2012 at 22:09
  • 2
    @gdoron Do you have some kind of fixation on bashing CoffeeScript? :S Commented Jun 3, 2012 at 0:05

1 Answer 1

3
$('.sidebar-nav a.active')

is different than...

$('div.sidebar-nav ul li a.active')

in the first case, a.active is a descendant of .sidebar-nav, and the structure under .sidebar-nav could be anything (list, article, spans, marquees, doesn't matter, as long as its in there somewhere). In the second, it is a great-grandchild, within a list. We'd need to see your HTML to be sure, but it looks like bad selectors...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.