Reputation: 2163
i was trying to get a result of the browsers window width and trying to put the result of math and condition in a variable , this is the code
var MyWidth = 1900;
var MyHeight = 900;
var height = $(window).height();
var width = $(window).width();
var AutoW = function () {
if ( (MyWidth / width).toFixed(2) > 0.95 )
return 1;
if ( (MyWidth / width).toFixed(2) < 1.05 )
return 1;
else return (MyWidth / width).toFixed(2);
};
alert(AutoW);
the problem is i don't know the right syntax or structure of the function assigned to the variable
what is the right way to code this ?
Upvotes: 1
Views: 96
Reputation: 1182
You should try this way:
(function(){
var MyWidth = 1900,
MyHeight = 900,
height = $(window).height(),
width = $(window).width(),
result;
var AutoW = function () {
var rel = (MyWidth / width).toFixed(2);
return ( ( rel > 0.95 ) && ( rel < 1.05 )) ? 1 : rel;
};
result = AutoW();
alert(result);
})();
But remember the function you wrote always returns 1, that is why I changed it for (&&) condition to make it a filter.
if you make alert of function, you will return the entire function. you have to asign the cast of a function "()" to a variable so the return will be asigned to it.
var result = f_name();
And remember, try not to use global variables, wrap everything in a function.
You should put {} after if, and cache values that you are using many times like when I cached "(MyWidth / width).toFixed(2)" into rel.
The sintax I used instead of if >> (condition) ? (return if match) : (return else);
Upvotes: 1
Reputation:
<script>
var MyWidth = 1900;
var MyHeight = 900;
var height = $(window).height();
var width = $(window).width();
var AutoW = function () {
if ((MyWidth / width).toFixed(2) > 0.95)
return 1;
if ((MyWidth / width).toFixed(2) < 1.05)
return 1;
else return (MyWidth / width).toFixed(2);
};
var val = AutoW();
alert(val)
</script>
Upvotes: 1
Reputation: 9056
var AutoW = function () {
// don't calculate ratio 3 times! Calculate it once
var ratio = (MyWidth / width).toFixed(2);
if (ratio > 0.95)
return 1;
if (ratio < 1.05)
return 1;
else return ratio;
};
// alert(AutoW); - this was a problem, AutoW is a function, not a variable
// so, you should call it
alert(AutoW());
Upvotes: 1
Reputation: 43245
alert(AutoW());
AutoW()
returns the value of function assigned to the variable.
fiddle : http://jsfiddle.net/V2esf/
Upvotes: 2