2

I'm trying to find a solution to make this code cleaner:

$(document).keypress(function(ev){
         if($("#dialog").is(':visible') === false && $("#alertDialog").is(':visible') === false){
            if(ev.keyCode=='13' && !$('#resetBtn').is(':focus') && !$('.edit-new').is(':focus') && !$('.edit-trash').is(':focus')){
                return validateForm('valueTable');
            } 
            if(ev.keyCode=='27'){
                $('#resetBtn').click();
            }
         }
     });

As you can see, I'm checking to see if three seperate inputs are not in foucs before exectuing my event. Is there a way to target #resetBtn, .edit-new, .edit-trash into one, nicely packed selector?

0

3 Answers 3

3

Would this do what you want?

$('#resetBtn:focus, .edit-new:focus, .edit-trash:focus').length === 0

You could use a similar statement for your visibility checks too.

Sign up to request clarification or add additional context in comments.

1 Comment

I like this solution a lot, but I decided to go with .is(':focus), as I think it's a bit more semantic. However, this notation would be great if I do anything else to the selections other than just see if they're there! Thank you very much!
2

Yes, like this $('#resetBtn, .edit-new, .edit-trash') :)

2 Comments

I swear I tried this solution before but it didn't work before. But this works perfectly!
This doesn't answer the question of how to tell whether any of these sub-selectors contain matches that are, or are not, focused.
1

You could use single selectors and simply check the length of their returned elements. No reason to explicitly check for equality with false when we can check the length property instead:

// Handle the keypress event on the document object
$(document).on("keypress", function (event) {
    // Proceed if no visible dialogs
    if (!$("#dialog:visible, #alertDialog:visible").length) {
        // Checking which key was pressed
        switch (event.which) {
            case 13:
                // If no focus is on #resetBtn, .edit-new, or .edit-trash
                if (!$("#resetBtn:focus, .edit-new:focus, .edit-trash:focus").length) {
                    return validateForm("valueTable");
                }
                break;
            case 27:
                // Trigger the click event on #resetBtn
                $("#resetBtn").trigger("click");
        }
    }
});

2 Comments

This is great at condensing my code! However, what's the difference between using .on vs .keypress?
$.fn.keypress internally calls $.on. By using $.on directly you get a negligible performance boost, plus it's far easier to implement event-delegation using $.on than it is using $.fn.keypress.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.