5

I'm doing an Ajax request with CoffeeScript and then rendering a partial from my controller, but then after that the partial has been rendered it can't use the Javascript I had previously.

Example:

At the end my action of my home_controller I have:

respond_to do |format|
   format.html { render partial: 'frame' }
end

In my home.js.coffee:

$('#plouf').click -> 
  alert('test')

Then in my partial _frame.html.erb (in the home folder of the views folder)

<span id="plouf">test<span>

If I click on this span, nothing happens...

<%= javascript_include_tag "application", "data-turbolinks-track" => true %>

But if I add this line in my partial it works, but I know it's ugly since I already did it in my application.html.erb

Am I missing something, or is it normal that partial can't use any previous Javascript?

1 Answer 1

9

Partials are compiled into the view before javascript is run by the browser.

What you need is

$(document).on 'click', '#plouf', ->
  alert('test')

This binds the event to the document, so when turbolinks or ajax reloads the HTML, your event handler is still active.

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

4 Comments

Thanks! I understand better now, but I had to rewrite as: $(document).on('click', '#plouf', ( -> alert('test')))
Please fix the commas, should be: $(document).on 'click', '#plouf', ->
@d_rail better? You can always suggest an edit too :)
what if I want to apply some js on render, not on particular event like click or change e.g. some datatable property.

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.