Reputation: 5178
I have jQuery
, jQuery-ujs
, and turbolinks
in my app (default dependencies in rails 5 apps).
When the submit button is clicked, I want to fadeIn
a loading spinner (animated spinner from font-awesome).
Assume that the loading spinner is hidden on the page. Here is the code for the submit button and the spinner:
<div class="actions">
<%= form.submit id: 'submit-btn' %>
</div>
<div id='load-icon'>
<i class="fa fa-refresh fa-spin fa-3x fa-fw" aria-hidden="true"></i>
<span class="sr-only">Refreshing...</span>
</div>
And then I have the following, which is supposed to put an event listener on that submit button, which fades in the spinner once the button is clicked:
$(document).on('turbolinks:load', function () {
$('#submit-btn').on('click', function(){
$('#load-icon').fadeIn();
});
});
The search takes a while to load the information, but the spinner does not appear. I know this has to either do with turbolinks, jQuery-ujs, or both which are stopping the javascript from executing when the button is clicked.
Ultimately my question is: How can I get javascript to run when a submit form button is clicked?
Upvotes: 1
Views: 63
Reputation: 7777
Look at the latest turbolinks
documentation. Use document.addEventListener("turbolinks:load", function() {
instead of $(document).on('turbolinks:load', function () {
. So, the code looks like this:
document.addEventListener("turbolinks:load", function() {
$('#submit-btn').on('click', function(){
$('#load-icon').fadeIn();
});
});
It was tested and it is working properly for me.
Upvotes: 1