revive
revive

Reputation: 863

jQuery Global variables are not accessible by functions

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 :D

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' );
    });
});

Upvotes: 1

Views: 5450

Answers (3)

Starx
Starx

Reputation: 78991

Try putting the variables outside the $(document).ready()

Upvotes: 0

Amr Elgarhy
Amr Elgarhy

Reputation: 68922

parentWidth is not a global variable it exist in the document.ready function but its not a global variable for any function.

Except if you declared this variable before the document.ready:
Something like this:

var parentWidth;
$(document).ready(function(){
parentWidth = $(this).parent().width();
....

The same goes with the other 2 variables.

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630429

When you're declaring this:

parentWidth = $(this).parent().width();

You're not getting the width of the parent of that element (the <input>), it's using document for this, since that's the context you're in. You need to get the width inside the function, either inside each or as a plugin, but not "globally" like this.

Upvotes: 2

Related Questions