Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is even better use jQuery handler?

I mean, if I have this handler :

$(document).ready(function() {
    $('.myElement').change(function() {
        // some
    });             
});

linked to "400" elements for example, it will be slower than

function myFunct() {
    // some
{

<select class="myElement'" onchange="myFunct(this);return false">
    // one of 400 elements. Each of this use that onchange link
</select>

because in fact I need to call that function only when I "change" somethings (so I don't understand why I need to handle 400 elements, worst of resource).

What do you think about?

like image 430
markzzz Avatar asked Dec 28 '22 15:12

markzzz


1 Answers

Yes it will be slower since the browser must attach a handler all of those elements, which could cause a "lag" on page load during which your user might be able to interact with elements which have no handler code attached to them.

You can still use jQuery in a performant way, however, using just one delegated handler.

$('#container').delegate(".myElement", "change", function () {
    myFuct(this);
    return false;
}); 

Update! jQuery 1.7 example (using .on):

$('#container').on("change", ".myElement", function () {
    myFuct(this);
    return false;
}); 
like image 155
karim79 Avatar answered Dec 30 '22 08:12

karim79