nonstic Random snippets of mac and rails goodness

Posted
10 December 2008 @ 4am

Tagged
Ruby, Rails

Chaining Javascript OnLoad Event Handlers (or How to Use the YM4R Plug-in and FancyZoom together in a Rails App)

I was building a Rails application today, and wanted to include Google Maps integration and use the FancyZoom Javascript library on the same page. These two javascript libraries both depend on being instantiated as part of the onload Event Handler. Normally, you load FancyZoom in the body tag thusly:

<body onload="setupZoom();">

However, if you have installed the YM4R plugin for Google Maps integration, you will have also added several lines to the <head> section of your rails layout template, something like this:

<%= GMap.header %>
<%= @map.to_html %>

What you may not know is that the @map.to_html call actually dumps a bunch of javascript code into your page template before it loads. This includes its very own onload call.

window.onload = addCodeToFunction(window.onload, ...

This adds an onload function, to instantiate your Google Map object when the page loads.

Now, you might think (as I did) that when you add the onload call to setupZoom(); on the <body> tag, it would just add the event onto the onload event handler. However, what it actually does is replace the earlier onload event handler. This means the Google Maps onload event never happens, so your map area shows up blank.

How to fix?

The javascript snippet that the @map.to_html inserts looks something like this:

<script type="text/javascript">
window.onload = addCodeToFunction(window.onload,function() {
    if (GBrowserIsCompatible()) {
    ... other javascriptyness ...
    }
});
</script>

So I simply added another call to the addCodeToFunction function provided by YM4R, to add the call to setupZoom to the onload chain. Both calls are then successfully made in the onload event handler, and all is good.

<script type="text/javascript">
    window.onload = addCodeToFunction(window.onload, setupZoom();)
</script>

I’ve glossed over a bunch of details, but hopefully this gives you enough info to put you on the right path. If you want more detail, just ask me, man.


No Comments Yet


There are no comments yet. You could be the first!

Leave a Comment