0

I've a div like this in a scala.html file of my template (I'm using PlayFramework):

<div id="box">Text in the box</div>

and this Coffee script:

$("#box").on "click", -> 
    $("#box").fadeOut()

It doesn't work: if I click the div #box nothing happens. I'm trying to use plain jquery to understand if it's a Coffee issue or not. Then I put the same jQuery script in <head>:

<script>
$("#box").on("click", function() {
    return $("#box").fadeOut();
 });
</script>

and doesn't work again but if I put it in the scala.html file (that contains the div #box) it works! Where is the error?

5
  • Hi @JonathanLonowski, yes I've tried with and without $(document).ready(function() {.... No errors in console. Commented Oct 18, 2013 at 9:41
  • In the html there's only one #box but I've tried to change it to another name and it's the same. With console.log the console says "Running" and "0" for .lenght Commented Oct 18, 2013 at 9:53
  • With $ -> at the top of Coffee (above the two console.log), it's the same. Console says again "Running" and "0" ! Commented Oct 18, 2013 at 10:03
  • Does delegated binding help? $(document).on 'click', '#box', -> ... Commented Oct 18, 2013 at 10:05
  • @JonathanLonowski: ok with the last code it works! Now I'm thinking a thing that probably is the problem: the div#box is loaded with an Ajax call by clicking a button, then before loading it doesn't exist. Is it the problem? And then what is the right way to make it works? Commented Oct 18, 2013 at 11:25

1 Answer 1

2

the div#box is loaded with an Ajax call by clicking a button, then before loading it doesn't exist. Is it the problem?

Yeah, that would cause it. And, delegated binding is generally the solution.

The reason for it is because jQuery can only bind events to elements that exist at that moment. But, since nearly all events bubble/propagate through the target's .parents(), an existing parent can be used to represent the intended descendant.

$(document).on 'click', '#box', ->
  # ...

In this case, document is the existing parent, allowing #box to have a click binding created for it before it exists in the DOM.

Otherwise, the binding of the event can be delayed until the element exists. This is what happens for the last part of your question, as the <script> is inserted into the DOM along with the <div>.

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.