Evanss
Evanss

Reputation: 23563

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

I have a div with a number of links. How can I create an event for when you focus to ANY of the links in this div and when you leave focus of 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>

So if a user uses keyboard navigation I need a single event (to call function A) when they focus on link1. I dont want any other events if they keep tabbing or click on links1-3 But when they tab out of the div or click elsewhere on the screen then I need a second event (to call function B).

Upvotes: 4

Views: 2312

Answers (3)

MrBizle
MrBizle

Reputation: 418

First you need to set up an event listener for the links

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

or with JQuery:

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

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

This code will run when ANY of the links are "focussed" (keyboard or otherwise). to stop this you can prevent event bubbling.

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

You will not however want to prevent event propagation for the first click. Comment if you need complete code :)

Then you will need a "focus out" event handler for the div

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

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

Upvotes: 1

lmgonzalves
lmgonzalves

Reputation: 6588

I think this is the solution for your (pretty 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

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

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's 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

Upvotes: 0

Related Questions