Only Bolivian Here
Only Bolivian Here

Reputation: 36743

Weird issue with simple CoffeeScript and jQuery events

The event fires well on a wildcard selector, but fails if I use a specific ID for the selector.

This works:

$("*").click ->
  console.log "entered event."
  $("#tellafriend").dialog
    modal: true
    buttons:
      Ok: ->
        $(this).dialog "close"

Yet, this doesn't:

$("#tell-a-friend").click ->
  console.log "entered event."
  $("#tellafriend").dialog
    modal: true
    buttons:
      Ok: ->
        $(this).dialog "close"

And my relevant HTML:

<ul class="actions">
    <li><a href="#">Home</a></li>
    <li>|</li>
    <li><a href="#" id="tell-a-friend">Tell a Friend</a></li>
</ul>

Am I missing something in CoffeeScript for this to work? Maybe jQuery selectors are formatted differently in CoffeeScript?

This is the rendered Javascript that my application serves (Rails convert CoffeeScript to JS when serving the pages):

(function() {

  $("#tell-a-friend").click(function() {
    console.log("works");
    return $("#tellafriend").dialog({
      modal: true,
      buttons: {
        Ok: function() {
          return $(this).dialog("close");
        }
      }
    });
  });

}).call(this);

Upvotes: 3

Views: 508

Answers (1)

tvanfosson
tvanfosson

Reputation: 532465

Is it possible that the code is being executed before the DOM is completely loaded. Try wrapping it in a document ready handler so that any click handlers are applied after the DOM is completely loaded. As it is, it may only be executing on the body element because that's the only element available at the time the script is executed.

Upvotes: 2

Related Questions