Shawn M. Kiewel
Shawn M. Kiewel

Reputation: 105

Javascript not firing on all turbolinks page loads

I have some javascript that is not firing on all turbolinks page loads. If you navigate to the page, javascript will not fire. If you refresh, javascript will work fine. It will also work fine on returns to the page after you have hit refresh.

Here is my view:

<%= javascript_pack_tag 'reports' %>
<h1>CSV Report</h1>
<div class="form-group row">
    <div class="col-2 col-form-label col-form-label">Start Date</div>
    <div class="col-3"><%= date_field_tag 'start_date', '',class: "form-control" %></div>
</div>
<div class="form-group row">
    <div class="col-2 col-form-label">End Date</div>
    <div class="col-3"><%= date_field_tag 'end_date', '',class: "form-control" %></div>
</div>
<div class="form-group row">
    <div class="col-2"><button id="get_csv" class="btn btn-primary">Get CSV</button></div>
</div>

Here is my javascript:

document.addEventListener("turbolinks:load", function() {
    $(document).on('click','#get_csv',function(e){
        var start_date = $('#start_date').val();
        var end_date = $('#end_date').val();
        if ( start_date == '' || end_date == '' || start_date > end_date ) { return; }
        document.location = '/reports/csv/download?start_date=' + start_date + '&end_date=' + end_date;
        //console.log( '/reports/csv/download?start_date=' + start_date + '&end_date=' + end_date);
    });
});

Suggestions?

Upvotes: 0

Views: 176

Answers (1)

Shawn M. Kiewel
Shawn M. Kiewel

Reputation: 105

Reading the turbolinks documentation more closely, I see that I misunderstood how to use event delegation. You're not supposed to put your event delegation into an eventListener listening for the turbolinks:load event. You're just supposed to bind once sitewide. So I moved

$(document).on('click','#get_csv',function(e){
        var start_date = $('#start_date').val();
        var end_date = $('#end_date').val();
        if ( start_date == '' || end_date == '' || start_date > end_date ) { return; }
        document.location = '/reports/csv/download?start_date=' + start_date + '&end_date=' + end_date;
        //console.log( '/reports/csv/download?start_date=' + start_date + '&end_date=' + end_date);
    });

to application.js and removed records.js. Problem solved.

Upvotes: 1

Related Questions