Can I write an onFocus / lostFocus handler for a DIV using JS or jQuery?

I have a div, and when the user clicks on the div, the function should be called. And when the user clicks something else (nothing but this div), another function should be called.

Basically, I need to have the onFocus () and lostFocus () function calls associated with this DIV. Is it available in JavaScript or even in jQuery?

Thanks.

+7
source share
4 answers

Here I created a working demo of what you want http://jsfiddle.net/kPbfL/1/

You need to add the tabindex attribute to the div :

Markup:

  <div id="mydiv" tabindex="-1"></div> 

Javascript

 $("#mydiv").focusin(function() { $("#mydiv").css("background","red"); }); $("#mydiv").focusout(function() { $("#mydiv").css("background","white"); }); 

CSS

 #mydiv{ width : 50px; height:50px; border : 1px solid red; }​​ 
+17
source

Focus does not work on DIV : http://api.jquery.com/focus/

Also good to read: jquery: focus on div does not work

 If you want to focus a div or anything normally can't be focused, set the tag tabindex to -1 first. eg: $("div#header").attr("tabindex",-1).focus(); 
+5
source

Not sure if this solution works for your webpage, but you can use jQuery on () to attach the click event to the body element and delegate it with a child div. Then, in the event handler, check the id attribute and the handle itself; something like:

 $(body).on("click", "div", function (evt) { if ($(this).attr("id") == "innerDiv") { handle inner div click here } else { hanlde out div click here { } 

Hope this helps ...

0
source

Of course.

 $("#your-div-id").focusin(function() { // code here }); $("#your-div-id").focusout(function() { // code here }); 
-one
source

All Articles