Wednesday, April 6, 2011

Speed up :visible:input selector avoiding filter

I have a jQuery selector that is running way too slow on my unfortunately large page:

$("#section").find(":visible:input").filter(":first").focus();

Is there a quicker way to select the first visible input without having to find ALL the visible inputs and then filtering THAT selection for the first? I want something like :visible:input:first but that doesn't seem to work.

[Edit] Here's the basic idea of what #section looks like:

<div id="section">
    <div>
        Some text <input type="text">
    </div>
    <div>
        etc. etc. <input type="text">
    </div>
</div>
From stackoverflow
  • $(":input:visible:first", "#section").focus();
    

    If you first filter for the type of control you avoid checking the :visible on all the #section's elements.

    It seems like you need only to catch the first input type="text" visible.
    This should be a bit faster.

    $("input[type='text']:visible:first", "#section").focus();
    
    Nick Craver : This is a different selector, `:input` != `input`
    Alex Bagnolini : Fixed, thank you.
    macca1 : Thanks, this update is about 80ms faster. However this selector is still costing 156ms in IE6. I feel like this should be a quick 16ms lookup or less. Is there any other way to optimizer this?
    macca1 : I'm accepting the first part of this answer. Seems like the fastest way possible of doing this. Thanks!
  • How about adding class="default_field" to the default field for each page, then using $('.default_field').focus();?

    How easy this is to do depends on your server-side technology of course, but the advantages are that it takes the processing burden off of the client (which is extra important for IE6), and it also gives you the flexibility to choose a default input other than the very first one on pages where it's appropriate.

0 comments:

Post a Comment