JavaScript — Accessing functions defined in jQuery scope / ReferenceError setInterval

To trigger a function defined in your document.ready function, you need to define a variable before the $(document).ready() that references the new function.

For example, function test() defined inside $(document).ready() is not accessible with setInterval('test()', 500), or something like onclick="javascript:test()"

$(document).ready( function() {
function test() { alert('test'); }
setInterval("test()", 500);
});

Will fail with ReferenceError

The following will work though:

var test;
$(document).ready( function() {
test = function() { alert('test'); };
setInterval("test()", 500);
});

Will work.

Advertisements

2 thoughts on “JavaScript — Accessing functions defined in jQuery scope / ReferenceError setInterval

  1. Woah! I’m really loving the templatetheme of this website. It’s simple, yet effective. A lot of times it’s hard to get that perfect balance between usability and visual appeal. I must say you have done a great job with this. In addition, the blog loads super quick for me on Firefox. Excellent Blog! dfacgdebdkga

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s