Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write onFocus/lostFocus handler for a DIV using JS or jQuery?

I have a div and when the user clicks the div a function should be called. And when the user clicks something else (anything other than this div) another function should be called.

So basically i need to have onFocus() and lostFocus() function calls associated with this DIV. Is it available in JavaScript or even in jQuery?

Thanks.

like image 812
Ivin Avatar asked Jul 01 '12 07:07

Ivin


People also ask

Can I use Onfocus on Div?

For example, you can use onfocus to show a popup when a div is clicked, and close the popup when anything else is clicked on the page (in the onblur event). Click to show another div. Click elsewhere to hide this div.

How to make focusout in jQuery?

The focusout() is an inbuilt method in jQuery which is used to remove focus from the selected element. Syntax: $(selector). focusout(function);

When an HTML element loses focus which event is called?

The onblur event occurs when an object loses focus. The onblur event is most often used with form validation code (e.g. when the user leaves a form field).

How do you know if an element loses focus?

The onfocusout event occurs when an element is about to lose focus. Tip: The onfocusout event is similar to the onblur event. The main difference is that the onblur event does not bubble. Therefore, if you want to find out whether an element or its child loses focus, you should use the onfocusout event.


2 Answers

You need to add tabindex attribute to div :

$("#mydiv").focusin(function() {
  $("#mydiv").css("background", "red");
});
$("#mydiv").focusout(function() {
  $("#mydiv").css("background", "white");
});
#mydiv {
  width: 50px;
  height: 50px;
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv" tabindex="100"></div>
<div id="anotherdiv"></div>
like image 128
Mohammad Adil Avatar answered Oct 05 '22 00:10

Mohammad Adil


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

ALso good read: jquery : focus to div is not working

If you want to focus a div or anything normally can't be focused, set the tag's tabindex to -1 first.
eg: $("div#header").attr("tabindex",-1).focus();
like image 36
Tats_innit Avatar answered Oct 05 '22 02:10

Tats_innit