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' %>
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 %>