hasFocus () check in tag a

1
Hi, good afternoon. I have the following HTML code:

<section class="sectionQuemSomos">
   <a class="iconQuemSomos" id="QuemSomos">
     <img class="img-fluid" style="height: 80px" src="assets/img/icos/Icone_Quemsomos.png">
   </a>
</section>

and the following JS code:

$(document).ready(function() {
    "use strict";
    var quemSomos = document.getElementById("QuemSomos");

  $(document).addEventListener('focus', function(){
    if (quemSomos === document.activeElement){
    alert("efds");
    }
  });
});

As simple as it sounds, I can not get this if statement to return true and get into your code block. I click on the tag to give it focus but no alert is displayed, so I know that this check is not working.

I'm trying to implement this eventListener so that this check can occur after the document is ready.

Thank you for your attention!

    
asked by anonymous 02.08.2018 / 18:19

2 answers

1

You will not be able to do this check on page load with the <a> element, as it is not autofocus and is not focused without the href attribute.

I see no reason to use the a tag this way, without being a clickable link, but if that's what you want, you have to use the tabindex attribute to make the element focus:

<a class="iconQuemSomos" id="QuemSomos" tabindex="0">

In this way you can detect the focus by using the focus event:

$(document).ready(function() {
   "use strict";
   $("#QuemSomos").on("focus",function(){
      console.log("foco");
   });
});
    
02.08.2018 / 18:52
1

hasFocus() is a method of the document object: developer.mozilla.org / Document / hasFocus

To check on javascript if an element has focus, compares with element in document.activeElement , which returns the current element with focus:

var quemSomos = document.getElementById("QuemSomos");
if (quemSomos === document.activeElement){
    alert("foco");
}

If you prefer to use jQuery , you can validate as follows:

if ($('#QuemSomos').is(":focus")){
    alert("foco");
}
    
02.08.2018 / 18:32