Add Global Javascript Variables to Window

javascript add global variable to window Just found out today that you can attach a javascript variable to the window effectively making it a variable global to the window. You can define it like this:

window.myboolean = false ;

And then you can access the same variable anywhere in your window. Pretty Cool Huh? The reason I needed a global variable in the first place was due to some neat javascript hackery. In some of my tables, I have made an entire row clickable , by adding onclick = “window.location.href = ‘’ ” to the <tr> element, and setting it’s style to render a cursor when moused over. I then paired this with rails url_for helper to give me a gmail esque feel. The user can click any part of the table row, not just a link, and they will be redirected. Sweet.

<tr  onclick = "window.location.href =  '<%= url_for :controller => 'manage', :id =>, :type => "whymail", :action => 'show' %>' "  style = "cursor:pointer:" >
    <td> My Content </td>

While clickable rows is a neat little trick,  what happens when you want to put a button or a checkbox in your table row to really get a gmail feel? When you click your button or your select box, you’re also clicking in the table row, so you automatically tell the browser to redirect to a different url. Make Sense?

<tr  onclick = "window.location.href =  '<%= url_for manage_spam_url(id)  %>' "  style = "cursor:pointer:" >
    <td> My Content </td>
    <td> <%= button_to_remote "Delete", :url => spam_survey_url(:id => , :update => "partial_update" %></td>



So in the above example even if you clicked on the Delete button then browser will still redirect to manage_spam_url because you still clicked on the table row. Therein lies the rub, and here comes the global javascript variables. To keep the table row redirecting us we can set a variable flag. First we put a ternary operator in the  table row like this:

<tr  onclick = "window.location.href = window.myboolean ? '#' : '<%= url_for manage_spam_url(id) %>' "  style = "cursor:pointer:" >

and we can set our flag in the header like this:

<script type="text/javascript" charset="utf-8">
    window.myboolean = false ;

Then in our button we can set the flag to true when it gets pressed:

<%= button_to_remote "Delete", :url => spam_survey_url(:id => , :update => "partial_update", :loading => "window.myboolean = true;",  :complete =>"window.myboolean=false;" %>

And after the javascript from the button loads we set the flag back to false. Its possible that this is serious over kill. But if anyone finds a better way to do this, let me know. Till then happy global javascripting!!

Leave a Reply

Your email address will not be published. Required fields are marked *