0

I'm having a few issues and I think it is because of the way I'm declaring an array. I'm using jQuery and I want to declare a global array so I can use its items inside my functions. The way I'm doing it now, when I do try to use the items in a function, they are limited. I did a console log of the array and it seems to show that it has stuff in it (even the stuff that I want) but then when I perform jQuery functions on those items it tells me

Cannot read property 'top' of undefined

Additionally, I've not used arrays much in JS, just in C++, so perhaps there's an issue with my syntax? Here is a rough copy of the code I have:

var pigs = new Array();
pigs[0] = $('#foo');
pigs[1] = $('#bar');

$(document).ready(function(){
    console.log(pigs);
    var topCoord = pigs[0].offset().top;
});
5
  • 1
    Does $('#foo') exists ? Commented Nov 13, 2013 at 14:42
  • 1
    $('#foo') wont return an element before document.ready Commented Nov 13, 2013 at 14:43
  • first of all, do you have '<div id="foo"></div>' and '<div id="bar"></div>' Commented Nov 13, 2013 at 14:43
  • and write pigs[0] = $('#foo'); pigs[1] = $('#bar'); inside document ready Commented Nov 13, 2013 at 14:44
  • 1
    I hope you enjoy JS?! The more beautiful way to do Arrays is for example: var pigs = []; -- then in document.ready just do pigs.push( $('#foo') ) to fill it :) Commented Nov 13, 2013 at 14:46

1 Answer 1

2

I guess $('#foo') and $('#bar') both return empty jQuery objects. You should wait for the DOM to be ready before querying it :

var pigs = new Array();
$(document).ready(function(){
    pigs[0] = $('#foo');
    pigs[1] = $('#bar');
    console.log(pigs);
    var topCoord = pigs[0].offset().top;
});
Sign up to request clarification or add additional context in comments.

4 Comments

If I assign those values in that function, will I still be able to use those objects and values in other functions? In other words, if I change it within that function, it will be changed globally as well right?
Yes sir. Welcome to Javascript ;-)
@mavsman Sure, because the array is defined inside the global scope.
Haha sadly, I've been using it for 6 months and never used arrays, yikes. Thanks for the help, it worked like a charm

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.