1

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?

2
  • Does it work if you call it in $(document).ready() ? Commented Jan 19, 2009 at 21:25
  • It should work -- there is no restriction or additional work to use jquery outside $(document).ready(). Can we see your mark up? Commented Jan 19, 2009 at 21:26

3 Answers 3

4

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.

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

Comments

1

I know it's kinda old thread but here's another solution. Might help others :D .
jQuery('#test').hide();

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.