gallagher gallagher - 5 months ago 29
jQuery Question

Convert jquery click function into angularJS directive

For a 'skip to content' accessibility link, this jquery in a controller works well:

$scope.skipLink = $( document ).ready(function() {
$(".skip").click(function(event){
var skipTo="#"+this.href.split('#')[1];
$(skipTo).attr('tabindex', -1).on('blur focusout', function () {
$(this).removeAttr('tabindex');
}).focus();
});
});


Where the HTML is

<a href="#content" class="skip sr-only sr-only-focusable">Skip to content</a>


Is there a way to rewrite this into a directive without using jquery?

Answer

In my opinion, I don't think this should be done without jQuery. In order to make it more angular-friendly however, see THIS DEMO.

The idea is to leverage the click handler directives from angular and let jQuery do its work inside of your controller.

AngularJS Controller

  $scope.skipToContent = function () {
    $("#content").attr('tabindex', -1);
  };
  $scope.removeTabIndex = function () {
    $("#content").removeAttr('tabindex'); 
  };

HTML

<a href="#content" 
   ng-click="skipToContent()"
   class="skip sr-only sr-only-focusable">Skip to content</a>
<input id="content" 
       ng-blur="removeTabIndex()"
       style="display: block; margin-top:100vh;"/>
Comments