views:

49

answers:

2

Hello.Here is my code :

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"&gt;&lt;/script&gt;
 <script type="text/javascript">
var toggle;
toggle=1;
function open(){
jQuery(window).bind("beforeunload", function(){$.post("logout.php");})
$.post("online.php",function(data){
$("#Layer6").html(data);
});
}

function toggle() 
{
$("#Layer4").animate({height:'toggle'});
$("#Layer6").animate({height:'toggle'});

if(toggle==1)
{
$("#toggle").attr('src',"toggle_up.jpg");
toggle=0;
}
else
{
$("#toggle").attr('src',"toggle_down.jpg");
toggle=1; 
}  

}

</script>

Here i have defined toggle as a global variable,and set its value to be 1 initially. When toggle() is executed,the value of toggle should change as its a global variable.Upon execution,the script doesn't seem to work at all(the toggle part).

Kindly help. Thanks !

+3  A: 

You've named your variable and function the same name ("toggle"). The function definition is overriding your variable declaration (since it comes afterward). Rename your function to something else, e.g. doToggle().

The reason that this conflict occurs is because you can assign function objects to variables in Javascript. Basically, when you call a function, Javascript looks for either a function with that name, or a variable with that name, in case it holds a reference to a function:

var variable = 3;
variable = function() { alert('Function called') };
variable();     // Calls the function, whose reference is stored in 'variable'
Cameron
thanks ! a ton :)
Anant
A: 

As Cameron pointed out the problem is that the variable and the function have the same name.

Also, keep in mind that jQuery has a method called .toggle()... This won't cause a conflict, since that's a method of $ or jQuery... but it might confuse someone reading your code.

Anyway, here is a more compact way to solve your problem:

var count = 1;

function toggle() 
{

    $("#Layer4").animate({height:'toggle'});
    $("#Layer6").animate({height:'toggle'});

    $("#toggle").attr('src',"toggle_" + (count++ % 2 ? "up" : "down") + ".jpg");

}

jsFiddle example page


The above uses the Javascript conditional operator to either concatenate up or down into the src attribute of #toggle.

(count++ % 2 ? "up" : "down") will first take count's current value (and then it increments its value) and mod it by 2. This value will either be 1 or 0. If it's 1 (true), up is concatenated. If it's 0 (false), down is concatenated. The incrementing is to keep track of the toggle.

As a note you can wrap your variables, functions, and any jQuery / other code that makes use of either in a self executing anonymous function, so as to minimize mucking the global namespace and to reduce the chance of variable name clashes if you later add more scripts to the page.

(function() { 
    var count = 1;
    function open() { ... }
    function toggle() { ... }
    $(function() {
        ...
    });
}());
Peter Ajtai