July 31, 2010

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()

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!