Reputation: 3002
Is it possible to prevent a mousedown in a div to steal focus, but allow text selection in this container (e.g. <div>
)?
/*// Version #1: Focus kept, but text is not selectable
$('div').on('mousedown', function(event) {
event.preventDefault();
});
/**/
// Version #2: Focus kept, text selectable, but focus is missing for a short time (flickering when css is applied to focused state)
$('div').on('mousedown', function(event) {
window.setTimeout(
function() {
$('input').focus();
}, 1
);
});
/**/
$('input').focus();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<div>A div container with some text, that should be selectable but not stealing focus of the input field</div>
My second version flickers, when just clicking the text (tested in current Chrome). In Firefox the selection always starts at the input field. Is there any better solution?
Upvotes: 1
Views: 1851
Reputation: 21802
The answer is right in front of your eyes :)
/*// Version #1: Focus kept, but text is not selectable
$('div').on('mousedown', function(event) {
event.preventDefault();
});
/**/
// Version #2: Focus kept, text selectable, but focus is missing for a short time (flickering when css is applied to focused state)
$('input').on('focusout', function(event) {
//setTimeout(function(){$('input').focus()}, 1);
});
/**/
//$('div').on('mouseup', function(event) {
// $('input').focus();
//});
$('html').on('mouseup', function(event) {
$('input').focus();
});
$('input').focus();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<div>A div container with some text, that should be selectable but not stealing focus of the input field</div>
The issue that if your mouseup
happens outside this div
, the focus is lost will persist.
Another approach would be to bind the mouseup
even on the html
, though this sounds a little excessive IMO, but seems to work.
The problem is that if you want focus to return to the input checkbox, you'll need to use the focusout
event, shown in the snippet. The other paradigm of "keeping" focus on the input box wouldn't work, because Javascript is synchronous and only one thing can run at a time.
Upvotes: 1