Thursday, February 24, 2011

How to find the active element id using jquery?

In many cases you wanted to know the element ID which is having the current focus. How will find out with out binding the focusin function.
Here is the solution:
Declare the jquery extended function like
jQuery.extend(jQuery.expr[':'], {
    focus: function (element) {
        return element == document.activeElement;
    }
});

The above function returns the active element details .
 
You can access the active element by using the ":" method. For example 
$(":").attr("id") . This statement will return the id of the element which is having the cursor position.
same way you can find which input textbox is active now.($("input:text:focus").attr("id")).

That's all you can able to find the active element id. 
Enjoy!!!!!!!!

2 comments:

  1. Thanks Vallab. The function $("input:text:focus").attr("id") works like a charm. :)

    ReplyDelete
  2. It works fine. But only in IE, not in Chrome. Haven't tried FF, Safari, Opera and other browsers.

    ReplyDelete