@bobdye's example doesn't work because <div>
elements aren't "focusable" by default.
You can force this behaviour by assigning a tabindex
property to the div, here is a fiddle.
HTML
<div class="defocus">.::.:.:.::.</div>
<div class="defocus">:..:.:.:..:</div>
<div class="defocus">.::.:.:.::.</div>
You add the class="defocus"
attribute to any element that needs to blur after x seconds.
CSS (relevant)
div:active {
color:lightcoral;
}
JavaScript
(function () {
window.addEventListener("load", function () {
var seconds = 0.15 * 1000;
var defocused = document.getElementsByClassName("defocus");
for (var i = 0, l = defocused.length; i < l; i++) {
var el = defocused[i];
el.style.outline = 0; //optional
el.setAttribute("tabindex", -1);
el.addEventListener("mousedown", blur);
}
function blur(e) {
var el = e.target;
setTimeout(function (el) {
el.blur();
}, seconds, el);
}
});
})();
- First we wrap this function in a seaf just as a commodity (it will prevent the blur function and variables from being accessible).
- Then we get all the elements with a
defocus
class.
- Then we iterate over them.
- First we eliminate the focus outline some browsers use because it looks ugly in a div, but it's up to you.
- Then we set a
tabindex="-1"
. Using -1
as an index prevents it from acting as a tab break point but allows it to recieve focus
and blur
events.
- Finally we add the
blur()
function to the mousedown
event which will defocus de element after x seconds.
- Then we define the
blur()
function which will take care of defocusing the element with a setTimeout()
.
That's it, hope it helps!
Note: I don't particularly care for the bounty, keep your rep!
Note: Thanks to @Adam for pointing out that seaf's variables need the var prefix to prevent them from being global.