james james - 4 months ago 29
Javascript Question

document.ready not firing?

This is NOT a case of not having jQuery loaded, but I do feel like I'm missing something else that's simple... On this staging site: https://hidden-tundra-8656.herokuapp.com/orders, once the page finishes loading, the "Camping & backpacking" should be auto-selected.

This is the code:

$(document).ready( function() {
console.log("about to trigger initial click")
$(".category-selector[data-id='"+gon.category_to_start+"']").click()
})


It's definitely not happening. Any thoughts? The only thing that I can think of is that the
category-selector
s are interpolated from Ruby, see view code below, so maybe that's causing it?

<div class="row">
<% @item_categories.each do |ic| %>
<div class="col-xs-6 category-box">
<div class="row category-row">
<div class="col-xs-12 table-display category-selector text-center" data-id="<%=ic.id%>">
<span class="labeler-response table-cell-display">
<%= ic.name %>
</span>
</div>
</div>
</div>
<% end %>
</div>


A little bit more info.

The
console.log
in the code is not triggered, and
gon.category_to_start
is defined. ALL of the other jquery on the page is working perfectly.

On this page, it is loading the
application.js
and a separate
orders/new.js
that contains the code in question. It loads jquery first, then
application.js
then
new.js
. For argument's sake, I just tried to load the code snippet into
application.js
and it didn't work there either. This works fine in local server.

Answer

If you're using Turbolinks (default if you setup a rails project), you should use page:load as an event.

$(document).on("page:load", function() {
  console.log("about to trigger initial click");
  $(".category-selector[data-id='"+gon.category_to_start+"']").click();
});

NOTE:

If you're in production mode, please make sure that you run bin/rake assets:precompile to keep your assets up-to-date.