views:

62

answers:

2

I have a site built with simple templates; header.tpl, navigation.tpl, body_home.tpl, body_about.tpl, body_anotherpage.tpl, etc. The navigation.tpl contains jQuery and is used to dynamically build a drop down navigation menu. When an element is clicked on the first drop down menu, the next is built based on what element was clicked. At some point there's no more drop downs and a variable is set, such as: var action = "dropdowncomplete". Now, in the body_*.tpl template files there's more jQuery which is ran when the action === "dropdowncomplete" evaluates to true. However, I don't know how to do this check with jQuery (nor with JS). Here's a simplified piece of code to illustrate how it works:

/* header.tpl (<head>) - setting this global variable */
var action = null;

/* navigation.tpl - for simplicity's sake, when link is clicked, the var is set */
$(document).ready(function() { 
$('a').live('click', function() { 
action = "dropdowncomplete"; 
}); }); 

/* body_*.tpl - this should be executed when the var is set, in this case when a link is clicked */
if(action === "dropdowncomplete") {
// do something
}

Note that all the above 3 pieces of JS/jQuery code are in separate script blocks!

Thanks.

A: 

I would use an hidden input in my html to store the value

Yassir
or even use $.data() if using jQuery - http://docs.jquery.com/Internals/jQuery.data
Russ Cam
+5  A: 

I think you're under the misapprehension that each <script> block is a separate scope. It isn't. If your code example above is an accurate reflection of your actual code, it should work, because action is declared globally, so the assignment is changing the global and the test is checking the global.

If it's not working, it's probably because you've established some other scope not shown above, like putting the var action = null bit inside a function.

Warren Young
Knowing it was probably a bug, I went through the code a few times and did find a "bug" in the code. The links have information in the href attribute that is used to generate the next drop down menu ( they contain information like foo=bar which is passed to a script with AJAX) so I have to use "return false" in the navigation.tpl at the end of the $('a').live('click', function() { }); block to prevent the link from redirecting to that url and that line breaks the execution of the code and so the following script blocks are not executed. Now I need a workaround for this problem.
TheMagician
Best post it as a separate question. This one's answered. :)
Warren Young