views:

16

answers:

2

Suppose I have an element on my page with id "some_id". I want to call a function as soon as I encounter this element. Something like following.

$("#some_id").call_a_function(function () {
  // do stuff
});
+1  A: 

Checkout this jquery plugin as an alternative to $(document).ready()

http://plugins.jquery.com/project/available

Allows you to specify a handler to a DOM element as soon as it becomes available.

Martijn Laarman
+1 - It's extremely annoying to get a downvote with no explanation, especially when you have seemingly answered the question. @Downvoter - We're all here to learn, enlighten us on why this answer deserved a downvote so we might further our knowledge.
Andy E
Thanks, I couldn't agree more. I guess people fear retaliation votes (i've had that happen to me too) too much.
Martijn Laarman
+1  A: 

Not sure what you mean by "encounter this element". If you mean as soon as the element is parsed, you could always inline some script right after it:

<div id="some_id">Hello</div>
<script type="text/javascript">
$("#some_id").call_a_function(function () {  
  // do stuff  
});  
</script>

The javascript code will be parsed right after the div. Of course, this wouldn't be much quicker than using $(document).ready() on small pages.

Andy E
"encounter this element" means as soon as it is available on the page.When we write "$("#some_id").click(function () {});", the anonymous 'function' would be called when that element is clicked. However what I want is to call that function as soon as it is available for manipulation.
Waseem
@Waseem: a script tag right after the element in the document will execute immediately after the element has been parsed (ie, as soon as it is available).
Andy E