AlexEfremo AlexEfremo - 4 months ago 59
Javascript Question

rails 4 with turbolinks and window load

I'm using Rails 4.

I'm trying to use this script to show google maps. I got a page with different places and each place got an address. It shows in google maps.

So i'm using pagination and on each page I got 4 places. 4 scripts of gmap.

But this scripts initializes only on page reload (ctrl+R or F5), that's because of turbolinks.

How can i make it work the easiest way?

function initialize() {
var myLatlng = new google.maps.LatLng(<%= place.latitude %>, <%= place.longitude %>);
var mapOptions = {
zoom: 16,
center: myLatlng
var map = new google.maps.Map(
document.getElementById("map-canvas-<%= %>"),
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: '<%= place.title %>'

google.maps.event.addDomListener(window, 'load', initialize);

that's the script. And div with each map looks like this:

<div id="map-canvas-<%= %>"></div>


You need to initialize scripts via turbolinks. Check this ASCIIcast about turbolinks.

In general, you need to change...

jQuery(function() {
  # your script

var ready;
ready = function() {
  # your script

$(document).on('page:load', ready);

All turbo links events you can find here.

Update for Turbolinks 5

page:load has changed to turbolinks:load, so instead you want to write:

var ready;
ready = function() {
  # your script

$(document).on('turbolinks:load', ready);

For more info, check out the README.