0

When I render an html.erb partial the div shows up on the screen but the javascript is not firing, how can I get the javascript to run?

Controller render

render partial: 'success', status: 200

Partial _success.html.erb

<div class="js-hide notification is-primary mb-16">
  Success!
</div>

<script language="javascript" type="text/javascript">
document.addEventListener("turbolinks:load", () => {
  alert('this should run');
  setTimeout(function() {
      $(".js-hide").hide();
  }, 5000);
})
</script>

Stimulus Form Controller

import { Controller } from 'stimulus';

export default class extends Controller {
  static targets = ['input', 'status', 'form'];

  success(event) {
      const [data, status, xhr] = event.detail;
      this.statusTarget.innerHTML = xhr.response;
      this.inputTarget.value = '';
      this.formTarget.remove()
  }

  error(event) {
    const [data, status, xhr] = event.detail;
    this.statusTarget.innerHTML = xhr.response;
    this.inputTarget.value = '';
  }
}

Input form

<div class="mb-24" data-controller="form">
  <p data-target="form.status"></p>
  <%= form_with(model: email_follow, url: form_path(event),
                data: { action: 'ajax:success->form#success 
                          ajax:error->form#error', target: 'form.form' }
                ) do |form| %>
        
        <div class="field has-addons">
          <div class="control">
            <%= form.text_field :name, class: 'input', data: { target: 'form.input' } %>
          </div>
          <div class="control">
            <%= form.submit 'Submit', class: 'button is-info' %>
          </div>
        </div>

  <% end %>
</div>

RESULT: Ended up adding the js code into my stimulus controller

1dolinski
  • 479
  • 3
  • 9
  • 29
  • Often, you'll see a [page change event](https://guides.rubyonrails.org/working_with_javascript_in_rails.html#page-change-events) handler. Have you looked into this? – jvillian Sep 11 '20 at 14:29
  • @jvillian good thought, nothing is firing though, even the alert – 1dolinski Sep 11 '20 at 14:46
  • Are you using Turbolinks? If so, you'll need to use the Turbolinks event handler. – jvillian Sep 11 '20 at 14:54
  • @jvillian yes using turbolinks and stimulus to watch the form input, added the form into the question – 1dolinski Sep 11 '20 at 14:59
  • @jvillian Not sure why that js doesn't run, I did find a solution, added the js into the stimulus controller that works just fine.. thanks for looking into this – 1dolinski Sep 11 '20 at 15:45

1 Answers1

0

I have experienced this issue as well, the problem is that content inserted with innerHTML will not execute any script tag within it. There are some more detailed discussions about this here.

Your option is either parsing the content and executing the scripts manually, or setting up other event listeners to catch that partial load.

Delong Gao
  • 89
  • 3
  • 5