Reputation: 7969
Hi I want to understand how function return value. I have two function one is working and second is not working. I want to know why is second function not working. http://jsfiddle.net/95vXQ/5/
Here is second function which is not working. I want to why it is not changing isVisible value
Upvotes: 0
Views: 136
Reputation: 3239
Very Simple.. Amit.
In your first case, it is a global variable so, once it is updated to False after hiding , it shows the div again.
Still not clear?
Upvotes: 0
Reputation: 5471
Your second example doesn't work as expected, since inside the function you are re-assigning a value true to isVisible
; and note that scope of isVisible
will be only inside the function, if you are declaring it inside click function.
If you just want to know the working of above examples, and not interested in declaring variable outside the function, then try this jsfiddle.
If you want to do a show/hide functionality, then try this toggle jsfiddle. Code below.
$(function(){
$("#btnShow").toggle(
function(){
$(this).val("Show");
$("#divContent").hide();
},
function(){
$(this).val("Hide");
$("#divContent").show();
}
);
});
Upvotes: 2
Reputation: 8846
jQuery click function is explained clearly in this link. The click function can be used to trigger a single or a series of jQuery events on click of an object. The variable declared in the function will be functional only within that click function. Values cannot be returned in a click function and only events can be triggered.
Upvotes: 2
Reputation: 46
It is variable Scope problem. Find more info here. To keep it simple, any variable that you defined inside a function is undefined outside the function.
And the function in second screenshot is failing because that function gets executed everytime there is a click event i.e., even if you are resetting isVisible value, it won't be carried to next call since you are initializing isVisible again with a true value set to it.
Upvotes: 2
Reputation: 4395
The second screenshot does not work because isVisible
is defined inside the click function. Once that function is complete isVisible
gets unset. When you call the click function again, isVisible
gets reset and it's value back to true. That is called variable scope.
And this problem has nothing to do with returned values. To return a value you'd have to use return [varname]
, and that would not help inside a click function.
Upvotes: 2