0

I've written a jQuery function which I intended to check when shift key is pressed specifically when a certain element has focus.

Below is the code I have written

$(document).keyup(function (e) {
    if (e.which === 9 && e.shiftKey) {
        if ($(".focus > a").focus) {
            alert("test");
        }
    }
});

However, the alert seems to function when shift key is pressed regardless of whether or not .focus > a has focus. Have I made an error here or is this a bug?

Richard
  • 86
  • 5

1 Answers1

0

if ($(".focus > a").focus will check if there is an attribute defined as focus at $(".focus > a") object. Due to it exists, your condition is always true.

so change to:

if $(".focus > a").is(":focus") .....

Using jQuery to test if an input has focus

messerbill
  • 5,499
  • 1
  • 27
  • 38
  • You shouldn't answer questions that are duplicates. And since you linked to that question, you know it is a duplicate. – Federico klez Culloca Mar 05 '18 at 15:21
  • @FedericoklezCulloca no i thought that the real point in THIS question is the way the `if` condition was designed, while the linked question directly asks for a way to check if it's focused. - this is why i've not marked dupe – messerbill Mar 05 '18 at 15:26
  • Check [this](https://meta.stackexchange.com/a/10844/150032), especially the "When are two questions considered duplicates?" section. To me, this falls into the second paragraph of that section. – Federico klez Culloca Mar 05 '18 at 15:30
  • `This includes not only word-for-word duplicates, but also the same idea expressed in different words.` - my idea was that there may be another if check like `if $( ".myClass).attr` or something else - in this case my short explanation at the top of my answer would also hit the point...i don't know whos opinion does fit better here...what do you think? – messerbill Mar 05 '18 at 15:45
  • 1
    I think that since no-one else in the community bothered to mark this as a duplicate, we're probably good as it is. Have a nice day :) – Federico klez Culloca Mar 05 '18 at 15:47