0

As I understand it any js file in the assets/javascripts folder is loaded if /= require_tree is present in the application.js file. I can't get my JS code to work, however. I have put it in assets/javascripts/locations.js and it doesn't work. When I put it in a script tag in my application.html.erb file it worked perfectly on the other hand. Any ideas what I could be missing? Running Rails 5.2. The JS code is below.

locations.js

var locations = ["coordinatesStore"]
  .map(id => document.getElementById(id));

Array.prototype.forEach.call(
  document.querySelectorAll('.add-button'),
  (button, i) => {
    button.addEventListener('click', () => getLocation(i));
  }
);

function getLocation(i) {
  var location = locations[i];
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(({ coords: { latitude, longitude }}) => {
      location.value = latitude + ", " + longitude;
    });
  } else { 
    location.value = "Geolocation is not supported by this browser.";
  }
}

I have this tag in my application.html.erb

<%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

1 Answer 1

1

Where is <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %> in your application.html.erb ?

Try putting it at the end of your body tag, at least after the <%= yield %>

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

3 Comments

Why is the tag in the head section of the erb file by default?
Because that's, by default and conventions, where the <script> tag to include an external .js file belongs. But "recently" (kind of), the best way was to include it after the HTML to not block the rendering of your page by loading external .js files. In your case, as the code is executed as soon it was imported, your javascript was run before there was any HTML in the page, so it wasn't working !
So the default setting is going to cause this same issue with everyone using Rails?

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.