1(function($) {
2
3  jQuery.extend(jQuery.expr[':'], {
4    focusable: function(el, index, selector){
5      var $element = $(el);
6      return $element.is(':input:enabled, a[href], area[href], object, [tabindex]') && !$element.is(':hidden');
7    }
8  });
9
10  function focusOnElement($element) {
11    if (!$element.length) {
12      return;
13    }
14    if (!$element.is(':focusable')) {
15      // add tabindex to make focusable and remove again
16      $element.attr('tabindex', -1).on('blur focusout', function () {
17        $(this).removeAttr('tabindex');
18      });
19    }
20    $element.focus();
21  }
22
23  $(document).ready(function(){
24    // if there is a '#' in the URL (someone linking directly to a page with an anchor)
25    if (document.location.hash) {
26      focusOnElement($(document.location.hash));
27    }
28
29    // if the hash has been changed (activation of an in-page link)
30    $(window).bind('hashchange', function() {
31      var hash = "#"+window.location.hash.replace(/^#/,'');
32      focusOnElement($(hash));
33    });
34  });
35
36})(jQuery);
37