views:

34

answers:

2

I am using jQuery to add placeholders to each text box on a page. I could just use $(document).ready() and then iterate through all the elements locating all those with the placeholder attribute and then adding the events to that element but this means that the user could click on the text box before the jQuery code is applied.

So I would like to apply the code as each text box is located. Does anyone know how to do this? I have been messing around with jQuerys event handling but I cant get it to work.

Thanks in advance.

+1  A: 

Take a look at the Live Query plugin:

Live Query also has the ability to fire a function (callback) when it matches a new element and another function (callback) for when an element is no longer matched. This provides ultimate flexibility and untold use-cases. For example the following code uses a function based Live Query to implement the jQuery hover helper method and remove it when the element is no longer matched.

$('li').livequery(function() { 
  // use the helper function hover to bind a mouseover and mouseout event
  $(this) .hover(function() { 
    $(this).addClass('hover'); 
  }, function() { 
    $(this).removeClass('hover'); 
  }); 
}, function() { 
  // unbind the mouseover and mouseout events 
  $(this).unbind('mouseover').unbind('mouseout');
});
cletus
I haven't used Live Query (and haven't seen the source), but if it checks for new elements using a high frequency timer then this would be no more useful than the `ready()` callback - since DOM parsing and javascript execution share the same thread any timers would be forced to wait until the thread became idle.
Andy E
@Andy Live Query comes down to a check for new elements every 20ms. But there is no way of escaping this because there isn't any native callback you can hook into so it's basically this or nothing.
cletus
A: 

Not an elegant solution, by any means, but a solution nonetheless would be to add a script tag after each text box:

<input type="text" id="input_1" />
<script type="text/javascript">
    $("#input_1").click(function ()
    {
        // ...
    });
</script>

You could even declare the callback function as a variable to make it a bit shorter.

Andy E