1

I have the following directive :

.directive('hasFocus',function(){
   return{
      restrict: 'A',
      link : function(scope,element,attrs){
           element.on('keydown',function(e){    
                switch(e.which){
                        case 38 : 
                            e.preventDefault(); 
                            selectNextButton($(this),true);
                        break;
                        case 40 : 
                            e.preventDefault(); 
                            selectNextButton($(this));
                        break;
                    }
                });
       }
   }
});

This works fine when I attach it to a button, but does not work when I attach to an anchor.

<button id="mybutton" has-focus>the button</button>


<a id="mybutton" data-ng-click="doSomething()" has-focus>the anchor</a>

I want to be able to capture e.which when the user is navigating using the directional arrows.

Is it not possible to bind a keydown event to an anchor ?


https://api.jquery.com/keydown/ states that it can :

"The keydown event is sent to an element when the user first presses a key on the keyboard. It can be attached to any element, but the event is only sent to the element that has the focus."

Fabii
  • 3,820
  • 14
  • 51
  • 92

1 Answers1

1

Seem like you can not set focus for anchor tag on click when there is no exist href attributes in your anchor. Here is an answer on stackoverflow which consists a list of DOM element that is able to receive focus. What you can do is to add in href attributes to anchor and it should work based on your expectation. Fiddle.

Community
  • 1
  • 1
themyth92
  • 1,743
  • 2
  • 17
  • 23