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.
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.
The focusout() is an inbuilt method in jQuery which is used to remove focus from the selected element. Syntax: $(selector). focusout(function);
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).
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.
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>
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With