Search code examples
jqueryclassevent-handlingonkeyup

Multiple classes on keyup jquery


I have a function that I want to execute on keyup for 2 different class of textfields. The code below works well when only one class is assigned to keyup but when I add a second class it works but there is a lot of lag. Either class by itself works fine so I assume I added the second class to the event handler improperly. The code is:

$(document).ready(function(){

    $(".class1").each(function() {

        //!!!!!!! .class2 here adds lag !!!!!!!!!!
        $('.class1,.class2').keyup(function(){
            myFunction1();

        });
    });

    $(".class2").each(function() {

        $(this).keyup(function(){
            myFunction2();
        });

    });
});

Solution

  • It appears you are wiring up too many events - hence the lag. You also don't need the .each, that's for iterating each element. Try simplifying as follows:

    $(document).ready(function(){
    
        $('.class1,.class2').keyup(function(){
            myFunction1();
            if ($(this).hasClass('class2')) {
                myFunction2();
            }
        });
    });