Fred K
Fred K

Reputation: 13910

JS script works only when embedded in scala/html code

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?

Upvotes: 0

Views: 311

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123563

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>.

Upvotes: 2

Related Questions