jQuery Global variables are not accessible by functions
Question by revive
I have a snippet of code, to calculate the width of some child items and instead of declaring the parentWidth and other variables in EVERY function.. I am trying to create Global variables to be re-used.. but, its not working.
Here is a portion of my code:
$(document).ready(function(){
parentWidth = $(this).parent().width(); // parent width in pixels
margin = parentWidth/100; // pixel equivalent of a 1% margin
border = 6; // 6px total border for each input field
$(".element.twoinone input").each(function() {
$(this).css( 'width',
(((parentWidth - (margin * 2)) - (border * 2)) / 2)
+ 'px' );
});
});
The parentWidth, margin and border variables are NOT accessed by the ‘each’ function (which I have multiple of). I’ve tried using live(), livequery(),.. etc.. but, no dice. I know its probably something simple that this noob is overlooking.. so any help is greatly appreciated !!
Thanks!
Also, if you have any input on calculating width percentages based on a parent containers width and accounting for each elements border, margin and qty,.. I’m all ears 😀
UPDATE
Isn’t this:
$(document).ready(function(){
parentWidth = $(this).parent().width();
$(".element.twoinone input").each(function() {
$(this).css( 'width',
(((parentWidth - (margin * 2)) - (border * 2)) / 2)
+ 'px' );
});
});
The same as this:
$(document).ready(function(){
$(".element.twoinone input").each(function() {
$(this).css( 'width',
((( $(this).parent().width() - (margin * 2)) - (border * 2)) / 2)
+ 'px' );
});
});
Answer by Starx
Try putting the variables outside the $(document).ready()