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:

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.

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?


Read Also:  Add custom page title and meta description only product pages in Shopify


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:

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

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

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 *