I have some plain HTML that provides some functionality when a link is clicked. I want to clean this up so that it is handled in a way that conforms to Ruby/Rails coding style. I tried messing with link_to helpers but couldn’t figure out a clean way to handle this situation.
<p>...or <a id="set_current_location" href="#">Use Current Location</a></p>
<script>
$(function(){
$('#set_current_location').on('click', function(e){
e.preventDefault();
navigator.geolocation.getCurrentPosition(function(position) {
$.ajax({
type: 'POST',
url: '<%= set_location_path %>',
data: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
},
async: false
});
})
});
});
</script>
Update: I’ve actually moved the javascript into a coffeescript file, so that’s not really my question. I’m really just wondering if this looks like a rails-like way to approach this problem.
The “rails way” would be to leave your javascript out of your view, using unobtrusive javascript in a separate file. At first glance, your code is fine – just move your “script” stuff into a .js file.