Detect focusin and focusout of an element containing multiple links with jQuery?

I have a div with multiple links. How can I create an event when you focus on ANY of the links in this div, and when you leave the focus in the ENTIRE div?

<a href="">LinkA</a>
<div class="links">
  <a href="">Link1</a>
  <a href="">Link2</a>
  <a href="">Link3</a>
  <a href="">Link4</a>
</div>
<a href="">LinkB</a>

Therefore, if the user uses keyboard navigation, I need one event (to call function A) when they focus on link1. I do not want any other events if they keep tabs or click links 1-3. But when they exit the div or click elsewhere on the screen, I need a second event (to call function B).

+4
source share
3 answers

I think this solution is for yours (quite easy to understand):

var prev = 0, current = 0;
$('*').on('click focus', function () {
    current = $(this).parent('.links').length;
    if(!prev && current){
        console.log('focus');   // Here call function A
    }else if(prev && !current){
        console.log('blur');    // Here call function B
    }
    prev = current;
});

Demo

0
source

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onfocus

JQuery:

https://api.jquery.com/focus/

$('a').focus(function(){ //event (funct a) });

, "" ( ). , .

$('a').focus(function(e){ e.preventDefault() // no event });

. , :)

"focus out" div

https://api.jquery.com/focusout/

$('div').focusout(function(){ //event (funct b) });
+1

I hope this meets your requirements

$(document).on('keydown click',function(e){
   if((e.type=="click" && e.target.tagName!="A")||(e.type=="keydown" && $(e.target).index()==($(".links a").length)-1))
   {
        //two or conditions to check, if event type is click and event target tagName != "A" i.e. anchor 
        //or event type is keydown and event has been triggered on last index
        //index calculated based on length of anchor tags present
        alert('Call function "B"'); //then call function B
   }
});

//a click focus event to only first anchor tag, which triggers irrespective of event.
$('.links a:first').on('focus',function(){
   alert('call function A'); 
});

Demo

0
source

Source: https://habr.com/ru/post/1607476/


All Articles