tags:

views:

789

answers:

2

I have created a function outside of $(document).ready(), but am still using jQuery inside of it. For example:

testFunction(){
  $('#test').hide();
  alert('test');
}

When I call testFunction() after the page has completely loaded, #test is not hidden but I do see the alert.

What must I do in order to use jQuery inside of this function? Thanks!

UPDATE:

Good to understand there are no restrictions for working outside $(document).ready().

Here's why it's not working: I am not calling testFunction(), I am calling parent.testFunction() from an iframe and #test is in the parent frame. So... I guess I cannot use '#test' as a selector. What should I be using?

A: 

Is there an element with an ID of test in the page?

Is JQuery loaded?

If you have added #test after loading the DOM, you will need to do some jiggling to rebind the elements to the DOM jQuery is using. That may be your issue.

Genericrich
+1  A: 

You can use '#test' as a selector, you just need to give jQuery some context, as it always assumes you're talking about an ID in the current document, not the parent:

// Selects the test element from the parent
var test = $('#test', parent)

EDIT
What context is jQuery being loaded from? The IFrame or the parent window? This can make a big difference.

I'd use an alert() to test if anything is found with jQuery. Call the alert() with the jQuery object as an argument.

alert($('#test'));
// or
alert($('#test').get(0));
// also try
alert(document.getElementById('test'));

If the last one doesn't work (it should alert 'HTMLElement', depending on the browser) then jQuery is not the problem.

Dan Herbert