Div - onblur function

Html

Html Problem Overview


I want to call an onblur on div. Not sure how to get it done.

Tried this:

div onblur="javascript:callme()"

but it didn't work

Html Solutions


Solution 1 - Html

For blur event to fire on an element, the element needs to receive focus first. But <div> elements do not receive focus by default.

You can add tabindex="0" or contentEditable to your div so it will receive focus.

See it in action: http://jsfiddle.net/t25rm/

Solution 2 - Html

The blur event fires when focus is lost. By default, a div element cannot have the focus in the first place so it can't be lost.

If you set tabindex on a div, then it can gain the focus, but you should almost always be using a more appropriate element (such as a button) when you think about making interactive controls.

<!-- Not recommended. See above -->
<div tabindex="1" onblur="callme()"> content </div>

Solution 3 - Html

If you give the div a tabindex attribute, it will be able to accept focus:

<div id="yourdivid" tabindex="0">content</div>

then attach focus and blur event handlers For example:

document.getElementById("yourdivid").onfocus = function() {
   alert('focused');
}
document.getElementById("yourdivid").onblur = function() {
   alert('blur');
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2357770View Question on Stackoverflow
Solution 1 - HtmlStrelokView Answer on Stackoverflow
Solution 2 - HtmlQuentinView Answer on Stackoverflow
Solution 3 - HtmlVoonicView Answer on Stackoverflow