0

I am trying to define a global jquery object variable so that I can access it from different functions.

This is what I am doing:

var object_list = $("#object_list");
var list_length = object_list.find("li").length;

$(document).on('keydown', '#object_list', function(event) {
    //both of these don't work
    alert(object_list);
    alert(list_length);
});

Well,, for some reason this is not working (the first alert gives me NULL and the second gives me 0, which is not).

Why aren't my global variables working..??

Thanks!!

3
  • 1
    #object__list and #object_list? Hmmmmm Commented Aug 17, 2013 at 15:06
  • And you wrapped that in document ready or inserted the script after the elements. Commented Aug 17, 2013 at 15:08
  • 1
    Also note that object_list would equal this inside the event handler, so it doesn't make much sense ? Commented Aug 17, 2013 at 15:09

3 Answers 3

2

This isn't a scope issue - there's a typo in your code:

var object_list = $("#object__list"); // 2 underscores

$(document).on('keydown', '#object_list', function(event) { // 1 underscore

So long as object_list and list_length are declared in a parent function this should work.

Alternatively, you could attach the variables to the window object, so they can be used anywhere at all in your code:

window.object_list = $("#object__list");
window.list_length = object_list.find("li").length;

As stated though, this should not be necessary given your code in the OP.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for catching the typo,,, but it was just my mistake copying the code... The typo doesn't exist in the original code.
0

What about this:

var object_list;
var list_length;

$(document).ready(function() {
    object_list = $("#object__list");
    list_length = object_list.find("li").length;
});

$(document).on('keydown', '#object_list', function(event) {
    alert(object_list);
    alert(list_length);
});

Comments

0

You're delegating event handling to document, and I assume that's because that #object_list does not exist in the page at the moment you bind the event. If it also doesn't exist at the moment you define object_list and list_length, that's why they're empty. And once empty, they won't be populated automatically when the elements are added. Try this:

$(document).on('keydown', '#object_list', function(event) {
    alert(this);
    alert($(this).find('li').length);
});

Comments

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.