Shinu Thomas
Shinu Thomas

Reputation: 5316

How to check if the last element inside another element is focused

Is there any jQuery code for finding the last <a> tag inside a <div> is focussed using keyboard. I.E. if the last <a> tag inside a <div> is focussed, a Javascript function has to be triggered

<div>
  <a>1</a>
  <a>2</a>
  <a>3</a>
  <!-- -->
  <!-- -->
  <a>n</a>
<div>

Upvotes: 0

Views: 355

Answers (2)

Faruk Yazici
Faruk Yazici

Reputation: 2404

Use :last-child selector to find the last element into <div> (in this case the last anchor <a>) and use also .focus(<callback>) to listen on focus event over any element:

$('div a:last-child').focus(function(){
    //Do whatever
});

Upvotes: 0

Alexis
Alexis

Reputation: 5831

just select the last a element and add focus eventlistener with JQuery

$("div a:last-child").focus(function(e){
  console.log("last <a> focused");
  e.preventDefault(); //prevent infinite loop
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <a href="#">a tag</a>
  <a href="#">a tag</a>
  <a href="#">a tag</a>
  <a href="#">a tag</a>
  <a href="#">a tag</a>
</div>

Upvotes: 2

Related Questions