Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 931
Only Bolivian Here Avatar asked May 26 '26 12:05

Only Bolivian Here


1 Answers

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.

like image 145
tvanfosson Avatar answered May 28 '26 02:05

tvanfosson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!