user2492270
user2492270

Reputation: 2285

Javascript & Jquery defining a global variable?

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!!

Upvotes: 0

Views: 79

Answers (3)

bfavaretto
bfavaretto

Reputation: 71939

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

Upvotes: 0

JustWork
JustWork

Reputation: 1964

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

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337714

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.

Upvotes: 2

Related Questions