user1386320
user1386320

Reputation:

How can determine which DOM object was clicked/focused with jQuery and blur event?

I have this HTML:

<div class="container">
    <a href="#mylink" tabindex="-1">select this</a>
    <a href="#mylink" tabindex="-1">select this</a>
    <a href="#mylink" tabindex="-1">select this</a>
</div>

<a href="#begin" tabindex="-1">click here to begin selecting</a>

And I have this JS/jQuery snippet of code:

$('a[href="#begin"]').blur(function(e) {
    console.log( e.target.href ); // this will output: #begin
});

So what I need with .blur is to determine which element got focus after the <a href="#begin"> was blured.

Is this possible with JS/jQuery?

Upvotes: 0

Views: 703

Answers (3)

musefan
musefan

Reputation: 48415

You can check which element gets focus by using the .focus method, similar to .blur

During your blur event, you can set a flag to "look out" for the next control focus. In your focus function, if this flag is set then you know your "being" field was the last one to lose focus. You will also need to reset the flag when any other field is blurred though.

Here is a simple concept example...

var beginWasLast = false;

$('a[href="#begin"]').blur(function(e) {
    e.preventDefault();
    beginWasLast = true;
    console.log( e.target.href ); // this will output: #begin
});

$('a[href="#begin"]').click(function(e) {
    e.preventDefault();
});

$('a:not(a[href="#begin"])').blur(function(e) {
    e.preventDefault();
    beginWasLast = false;
});

$('a:not(a[href="#begin"])').click(function(e) {
    e.preventDefault();
    if(beginWasLast){
        console.log( e.target.href );
    }
});

Here is a working example

I added in the e.preventDefault(); calls so that the page didn't reload when the links were clicked.

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

An other possible way could be: SEE DEMO

$('a[href="#begin"]').blur(function(e) {
  setTimeout(function(){console.log( $(document.activeElement).attr('href') );},0); 
});

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

It's not possible to know which element got the focus from the blur event itself. You would need to add a click event to get that, like this:

$('a[href="#begin"]')
    .blur(function(e) {
        console.log( e.target.href ); // previous link href
    });
    .click(function(e) {
        console.log( e.target.href ); // current link href
    });

Upvotes: 1

Related Questions