What's the best way to limit focusable controls to current dialog? - javascript

I've a web application with dialogs. A dialog is a simple div-container appended to the body. There is also an overlay for the whole page to prevent clicks to other controls. But: Currently the user can focus controls that are under the overlay (for example an input). Is there any way to limit the tabbable controls to those which are in the dialog?
I am using jQuery (but not using jQueryUI). In jQueryUi dialogs it's working (but I don't want to use jQueryUI). I failed to figure out, how this is accomplished there.
Here is the jQueryUI example: http://jqueryui.com/resources/demos/dialog/modal-confirmation.html - The link on the webpage is not focusable. The focus is kept inside the dialog (the user cannot focus the urlbar of the browser using tab).
HTML:
I should not receive any focus
<input type="text" value="No focus please" />
<div class="overlay">
<div class="dialog">
Here is my dialog<br />
TAB out with Shift+Tab after focusing "focus #1"<br />
<input type="text" value="focus #1" /><br />
<input type="text" value="focus #1" /><br />
</div>
</div>
CSS:
.overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.3);
text-align: center;
}
.dialog {
display: inline-block;
margin-top: 30%;
padding: 10px;
outline: 1px solid black;
background-color: #cccccc;
text-align: left;
}
Here is my fiddle: http://jsfiddle.net/SuperNova3000/weY4L/
Does anybody have an idea? I repeat: I don't want to use jQueryUI for this. I'd like to understand the underlying technique.

I've found an easy solution for this issue after hours of trying. I think the best way is adding 2 pseudo elements. One before and one after the dialog (inside the overlay). I'm using <a>-Tags which are 0x0 pixels. When reaching the first <a>, I'm focusing the last control in the dialog. When focusing the last <a>, I'm focusing the first control in the dialog.
I've adapted the answer of this post: Is there a jQuery selector to get all elements that can get focus? - to find the first and last focusable control.
HTML:
<div class="overlay">
<a href="#" class="focusKeeper">
<div class="dialog">
Here is my dialog<br />
TAB out with Shift+Tab after focusing "focus #1"<br />
<input type="text" value="focus #1" /><br />
<input type="text" value="focus #1" /><br />
</div>
<a href="#" class="focusKeeper">
</div>
Extra CSS:
.focusKeeper {
width: 0;
height: 0;
overflow: hidden;
}
My Javascript:
$.fn.getFocusableChilds = function() {
return $(this)
.find('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object:not([disabled]), embed, *[tabindex], *[contenteditable]')
.filter(':visible');
};
[...]
$('.focusKeeper:first').on('focus', function(event) {
event.preventDefault();
$('.dialog').getFocusableChilds().filter(':last').focus();
});
$('.focusKeeper:last').on('focus', function(event) {
event.preventDefault();
$('.dialog').getFocusableChilds().filter(':first').focus();
});
May be I'll add a fiddle later, no more time for now. :(
EDIT: As KingKing noted below the focus is lost, when clicking outside the control. This may be covered by adding an mousedown handler for the .overlay:
$('.overlay').on('mousedown', function(event) {
event.preventDefault();
event.stopImmediatePropagation();
});
EDIT #2: There's another thing missing: Going outside the document with the focus (for example the titlebar) and than tabbing back. So we need another handler for document which puts back the focus on the first focusable element:
$(document).on('focus', function(event) {
event.preventDefault();
$('.dialog').getFocusableChilds().filter(':first').focus();
});

You can try handling the focusout event for the .dialog element, check the e.target. Note about the e.relatedTarget here, it refers to the element which receives focus while e.target refers to the element lossing focus:
var tabbingForward = true;
//The body should have at least 2 input fields outside of the dialog to trap focusing,
//otherwise focusing may be outside of the document
//and we will loss control in such a case.
//So we create 2 dummy text fields with width = 0 (or opacity = 0)
var dummy = "<input style='width:0; opacity:0'/>";
var clickedOutside = false;
$('body').append(dummy).prepend(dummy);
$('.dialog').focusout(function(e){
if(clickedOutside) {
e.target.focus();
clickedOutside = false;
}
else if(!e.relatedTarget||!$('.dialog').has(e.relatedTarget).length) {
var inputs = $('.dialog :input');
var input = tabbingForward ? inputs.first() : inputs.last();
input.focus();
}
});
$('.dialog').keydown(function(e){
if(e.which == 9) {
tabbingForward = !e.shiftKey;
}
});
$('body').mousedown(function(e){
if(!$('.dialog').has(e.target).length) {
clickedOutside = true;
}
});
Demo.

Related

How do i make the input to show infobox even when i click on the show button without glitching

I have a code where I am showing a infobox when user clicks on an input field. This works fine but to make the UX better I would like the infobox to remain open when user clicks on a show button. It shouldn't close and open again
<div class="text-field">
<input type="text" class="username" name="username" placeholder="username" />
<button class="show-pwd">show</button>
</div>
<div class="info" style="display: none;">
<p>hello world</p>
</div>
$(function() {
const username = $('.username');
const showPwd = $('.show-pwd');
showPwd.click(()=>{
username.get(0).type = 'password';
$('.info').show();
});
$('.username').on("focus",(e)=>{
$('.info').show();
});
$('.username').on("blur",(e)=>{
$('.info').hide();
});
});
.text-field input {
border: none;
background-color: transparent;
}
.text-field {
background-color: lightblue;
width: 200px;
height: 25px;
}
.info {
background-color: lightgreen;
width: 200px;
height: auto;
}
heres the codepen
I tried to add the show method in click handler but that just adds a glitch
The blinking is happening because input blurring is triggered first, and then the button click.
You can avoid the blinking with a slight delay when blurring / moving out of the input, like in the following example.
const username = $('.username');
const showPwd = $('.show-pwd');
var btnClicked = false; // this is new
showPwd.click(()=>{
btnClicked = true; // this is new
username.get(0).type = 'password';
$('.info').show();
});
$('.username').on("focus",(e)=>{
$('.info').show();
});
$('.username').on("blur",(e)=>{
setTimeout(function() {
if(!btnClicked) {
$('.info').hide();
}
},100);
});
.text-field input {
border: none;
background-color: transparent;
}
.text-field {
background-color: lightblue;
width: 200px;
height: 25px;
}
.info {
background-color: lightgreen;
width: 200px;
height: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="text-field">
<input type="text" class="username" name="username" placeholder="username" />
<button class="show-pwd">show</button>
</div>
<div class="info" style="display: none;">
<p>hello world</p>
</div>
One suggestion - since the current setup (and the original one) have no way of hiding the .info div once the button has been clicked, consider making your .show-pwd button a toggle button - one click to show the info div (if it's not visible), and another to hide it (if it's visible).
If you decide to do that, you would have to change my initial suggestion a bit, in order to avoid hiding the info div when moving from your input to your button.
And if you're up for some UX suggestions, you could change the show button - for example, you could use the open / closed eye icon to reflect what would happen on button click (similar to show / hide password in various online services, like Gmail, and the like).

Focusing using javascript doesn't show outline style for checkbox like it does when use Tab

When navigating through inputs on the page using tab, they become outlined once in focus. But when I try to do something similar using, for example, arrow keys, focusing on checkboxes doesn't show outline styles.
jq(elems).keydown(function(e){
if(!e) return;
if(e.keyCode == '38') {
var el = ... // searching for the next element
el.focus();
}
Even if I manually add outline styles after focus, or add css like
input[type="checkbox"]:focus
{
outline-style:auto;
outline-color:
-webkit-focus-ring-color;
}
it wouldn't work. The focus is on the checkbox, the styles are there, but they are not displayed. Some other styles applied correctly, for example if I add styles like:
input[type="checkbox"]:focus {
box-shadow:1px 1px lightgrey;
}
I can see shadow box when focus is on the checkbox, but outline is not there.
I've only done this in raw js, but hopefully it helps:
Make sure to set the event listener on the document - otherwise you're only firing the event if the key is pressed whilst already 'inside' the element.
JS:
var el = document.getElementById('my-check');
document.addEventListener('keydown', function(e) {
e.preventDefault();
el.focus();
});
CSS:
input[type="checkbox"]:focus, input[type="checkbox"]:active {
width: 100px;
height: 100px;
outline-color: -webkit-focus-ring-color;
outline-style: solid !important;
}
DOM:
<form>
<input type="checkbox" id="my-check" />
</form>
Fiddle: https://jsfiddle.net/radmpxgs/1/
Sorry for the edits.

HTML: how to prevent moving focus from element?

I have several elements with tabindex attribute. When I click on any area of the page outside of them, they lose focus.
Current Behaviour - In regular desktop applications, if an element is not focusable, clicking on it doesn't move focus from a previous focused element.
But In HTML it's not the case: my focusable elements always lose focus, even if I click on elements with no tabindex.
Required Behaviour - Is it possible to prevent the above behaviour in HTML? I want my elements to lose focus only when I click on other focusable elements like its having in desktop application as I mentioned above.
This is a sort of hack and can be implemented in a better way.
Logic
Create a global variable lastSelectedInput to store id of last visited element.
Add a class to define boundary.
Add a click event on body and if event.path does not contains boundary element, call focus of lastSelectedInput
JSFiddle
Code
(function() {
var lastSelectedInput = "";
function bodyClick(e) {
var inside = false;
for (var i in e.path) {
if (e.path[i].className == "content") inside = true;
}
if (!inside) {
document.getElementById(lastSelectedInput).focus();
}
}
function inputFocus(e) {
lastSelectedInput = e.target.id;
e.stopPropagation()
}
function registerEvents() {
document.getElementsByTagName("body")[0].addEventListener("click", bodyClick);
var inputs = document.getElementsByTagName("input")
for (var i = 0; i < inputs.length; i++) {
inputs[i].onfocus = inputFocus;
}
}
registerEvents();
})();
.content {
margin: 15px;
background: #ddd;
border: 2px solid gray;
border-radius: 4px;
height: 200px;
width: 200px;
padding: 5px;
}
<div>
<div class="content">
<input type="text" id="txt1">
<input type="text" id="txt2">
<input type="text" id="txt3">
<input type="text" id="txt4">
<input type="text" id="txt5">
</div>
</div>

stopImmediatePropagation() of sibling not working

I show a search field on some text click, and hide it on search input blur.
But if I click on the search button I don’t want to hide the input field, and prevent it from being hidden (because of the blur). I tried to stopImmediatePropagation() without any luck.
Here’s some code:
// Not working. when search button is pressed, disable hiding the search input
$('.search-contacts-container > button').on('click touchstart', function(e) {
alert('xxx');
e.stopImmediatePropagation();
})
// when search input is blurred, hide it
$('#search-contacts').on('blur', function() {
$('.search-contacts-container').addClass('visuallyhidden');
$('#search-contacts').attr('required', 'false').blur();
})
// when search input is focused, show it
$('#search-contacts').on('focus', function() {
$('.search-contacts-container').removeClass('visuallyhidden');
$('#search-contacts').attr('required', 'true');
})
// on search text click, show the search input
$('.js-show-search').on('click touchstart', function() {
if ($('.search-contacts-container').is('.visuallyhidden')) {
$('.search-contacts-container').removeClass('visuallyhidden');
$('#search-contacts').attr('required', 'true').focus();
} else {
$('.search-contacts-container').addClass('visuallyhidden');
$('#search-contacts').attr('required', 'false').blur();
}
})
HTML:
<span class="js-show-search" title="Search for contacts">Search</span>
<form action="search" method="post" class="form-search search-contacts-container visuallyhidden">
<input type="text" id="search-contacts" placeholder="Search" required="false" />
<button type="submit" class="form-search__button" title="Search"></button>
</form>
Demo: http://jsfiddle.net/un775/
Any ideas?
Check out my new JsFiddle. I use this method on day to day tasks. I hope it helps you.
Basically what you are doing is adding a background that masks everything behind it, and then adding a click even listener to it that hides everything. The form/input is in front of the background allowing you to interact with it.
HTML
<div id="js-show-search">...</div>
<form id="search-contacts" class="hide">...</form>
<div id="background" class="hide"></div>
JavaScript
var searchContact, background;
searchContact = $('#search-contacts');
background = $('#background');
$('#js-show-search').on('click', function(){
//remove .hide to show elements
});
$('#background.close').on('click', function(){
//add .hide to hide elements
});
CSS
html, body {
height: 100%;
}
#background {
height: 100%;
width: 100%;
position: absolute;
top:0;
left: 0;
z-index: 0;
}
#search-contacts {
position: relative;
z-index: 1;
display: inline-block;
}
.hide {
display: none!important;
}
http://jsfiddle.net/un775/7/

Forcing a tab stop on a hidden element? Possible?

The site is here
I have opt to using the radiobutton's labels as customized buttons for them. This means the radio inputs themselves are display:none. Because of this, the browsers don't tab stop at the radio labels, but I want them to.
I tried forcing a tabindex to them, but no cigar.
I have came up with just putting a pointless checkbox right before the labels, and set it to width: 1px; and height 1px; which seems to only really work on chrome & safari.
So do you have any other ideas for forcing a tab stop at those locations without showing an element?
Edit:
Just incase someone else comes by this, this is how I was able to insert small checkboxes into chrome & safari using JQuery:
if ($.browser.safari) {
$("label[for='Unlimited']").parent().after('<input style="height:1px; width:1px;" type="checkbox">');
$("label[for='cash']").parent().after('<input style="height:1px; width:1px;" type="checkbox">');
$("label[for='Length12']").parent().after('<input style="height:1px; width:1px;" type="checkbox">');
}
Note: $.browser.webkit was not becoming true...so I had to use safari
a working solution in my case to enable tab selection / arrow navigation was to set the opacity to zero rather than a "display: none"
.styled-selection input {
opacity: 0; // hide it visually
z-index: -1; // avoid unintended clicks
position: absolute; // don't affect other elements positioning
}
Keep the radio input hidden, but set tabindex="0" on the <label> element of reach radio input.
(A tab index of 0 keeps the element in tab flow with other elements with an unspecified tab index which are still tabbable.)
If you separate the label from any field and set a tabIndex you can tab to it and capture mouse and key events. It seems more sensible to use buttons or inputs with type="button",
but suit yourself.
<form>
<fieldset>
<input value="today">
<label tabIndex="0" onfocus="alert('label');">Label 1</label>
</fieldset>
</form>
I have an alternative answer that I think has not been mentioned yet. For recent work I've been reading the Mozilla Developer Docs MDN Docs, Forms, especially the Accessibility Section MDN Docs, Accessible HTML(5), for information related to keyboard accessibility and form structure.
One of the specific mentions in the Accessibility section is to use HTML5 elements when and where possible -- they often have cross-browser and more accessible support by default (not always true, but clear content structure and proper elements also help screen reading along with keyboard accessibility).
Anyway, here's a JSFiddle: JSFiddle::Keyboard Accessible Forms
Essentially, what I did was:
shamelessly copy over some of the source code from a Mozilla source code to a JSFiddle (source in the comments of the fiddle)
create a TEXT-type and assign it the "readonly" HTML5 attribute
add attribute tabindex="0" to the readonly
Modify the "readonly" CSS for that input element so it looks "blank" or hidden"
HTML
<title>Native keyboard accessibility</title>
<body>
<h1>Native keyboard accessibility</h1>
<hr>
<h2>Links</h2>
<p>This is a link to Mozilla.</p>
<p>Another link, to the Mozilla Developer Network.</p>
<h2>Buttons</h2>
<p>
<button data-message="This is from the first button">Click me!</button>
<button data-message="This is from the second button">Click me too!
</button>
<button data-message="This is from the third button">And me!</button>
</p>
<!-- "Invisible" HTML(5) element -->
<!-- * a READONLY text-input with modified CSS... -->
<hr>
<label for="hidden-anchor">Hidden Anchor Point</label>
<input type="text" class="hidden-anchor" id="hidden-anchor" tabindex="0" readonly />
<hr>
<h2>Form</h2>
<form name="personal-info">
<fieldset>
<legend>Personal Info</legend>
<div>
<label for="name">Fill in your name:</label>
<input type="text" id="name" name="name">
</div>
<div>
<label for="age">Enter your age:</label>
<input type="text" id="age" name="age">
</div>
<div>
<label for="mood">Choose your mood:</label>
<select id="mood" name="mood">
<option>Happy</option>
<option>Sad</option>
<option>Angry</option>
<option>Worried</option>
</select>
</div>
</fieldset>
</form>
<script>
var buttons = document.querySelectorAll('button');
for(var i = 0; i < buttons.length; i++) {
addHandler(buttons[i]);
}
function addHandler(button) {
button.addEventListener('click', function(e) {
var message = e.target.getAttribute('data-message');
alert(message);
})
}
</script>
</body>
CSS Styling
input {
margin-bottom: 10px;
}
button {
margin-right: 10px;
}
a:hover, input:hover, button:hover, select:hover,
a:focus, input:focus, button:focus, select:focus {
font-weight: bold;
}
.hidden-anchor {
border: none;
background: transparent!important;
}
.hidden-anchor:focus {
border: 1px solid #f6b73c;
}
BTW, you can edit the CSS rule for .hidden-anchor:focus to remove the highlight for the hidden anchor if you want. I added it just to "prove" the concept here, but it still works invisibly as requested.
I hope this helps!
My preference:
.tab-only:not(:focus) {
position: fixed;
left: -999999px;
}
<button class="tab-only">Jump to main</button>
Another great option would be to nest your input + div in a label and hide the input by setting width and height to 0px instead of display: none
This method even allows you to use pseudo-classes like :focus or :checked by using input:pseudo + styleDiv
<label>
<input type="radio">
<div class="styleDiv">Display text</div>
</label>
input
{
width: 0px;
height: 0px;
}
input + .styleDiv
{
//Radiobutton style here
display: inline-block
}
input:checked + .styleDiv
{
//Checked style here
}
Discard the radio-buttons and instead; keep some hidden fields in your code, in which you store the selected value of your UI components.

Categories

Resources