Make an HTML element non-focusable - html

Is it possible to make an HTML element non-focusable?
I understand that a list of elements that can receive focus can be defined and that a user can navigate through these elements by pressing a Tab key. I also see that it is up to the browser to control this.
But maybe there is a way to make certain elements non-focusable, say I want a user to skip a certain <a> tag when pressing a Tab.

unfocusable
A negative value means that the element should be focusable, but should not be reachable via sequential keyboard navigation.
See also: developer.mozilla.org

To completely prevent focus, not just when using the tab button, set disabled as an attribute in your HTML element.
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<input class="form-control" type="text"> Click this, you can see it's focusable.
<input class="form-control" type="text" readonly> Click this, you can see it's focusable.
<input class="form-control" type="text" readonly tabindex="-1"> Click this, you can see it's focusable. Not tab'able.
<input class="form-control" type="text" disabled> Click this, you can see it's <strong>not</strong> focusable.

In order to make an prevent an element from taking focus ("non-focusable"), you need to use Javascript to watch for the focus and prevent the default interaction.
In order to prevent an element from being tabbed to, use tabindex=-1 attribute.
Adding tabindex=-1 will make any element focusable, even div elements. This means when a user clicks on it, it would likely get a focus outline, depending on the browser..
You would ideally, want this:
/**
* #this {HTMLElement}
* #param {FocusEvent} event
* #return {void}
*/
function preventFocus(event) {
if (event.relatedTarget) {
// Revert focus back to previous blurring element
event.relatedTarget.focus();
} else {
// No previous focus target, blur instead
this.blur();
// Alternatively: event.currentTarget.blur();
}
}
/* ... */
element.setAttribute('tabindex', '-1');
element.addEventListener('focus', preventFocus);
For safe typechecking, you can perform if (event.relatedTarget instanceof HTMLElement) instead if (event.relatedTarget).

TabIndex is what your looking for: http://www.w3schools.com/jsref/prop_html_tabindex.asp.
When you set a tabIndex value to -1 you will skip it when tabbing through your form.

In case you are looking for a global solution:
Link
document.body.addEventListener('focusin', (e) => {
if (e.target.classList.contains('__nofocus')) {
e.relatedTarget ? e.relatedTarget.focus() : e.target.blur();
}
});
It should work for anchors, buttons and anything else that can receive focus by default. Don't forget to set tabindex="-1" as well as the element would be unpassable by Tab-key navigation.

For the element you do not want to be focused on tab, you have to put the tabindex as a negative value.

I used focusable="false", because tabindex="-1" was not working in IE.

Making a focusable-by-default HTML element a non-focusable one isn't possible without JavaScript.
After diving into focus-related DOM events, I've came up with the following implementation (based on the #ShortFuse's answer, but fixed some issues and edge cases):
// A focus event handler to prevent focusing an element it attached to
onFocus(event: FocusEvent): void {
event.preventDefault();
// Try to remove the focus from this element.
// This is important to always perform, since just focusing the previously focused element won't work in Edge/FF, if that element is unable to actually get the focus back (became invisible, etc.): the focus would stay on the current element in such a case
const currentTarget: any | null = event.currentTarget;
if (currentTarget !== null && isFunction(currentTarget.blur))
currentTarget.blur();
// Try to set focus back to the previous element
const relatedTarget: any | null = event.relatedTarget;
if (relatedTarget !== null && isFunction(relatedTarget.focus))
relatedTarget.focus();
}
// Not the best implementation, but works for the majority of the real-world cases
export function isFunction(value: any): value is Function {
return value instanceof Function;
}
This is implemented in TypeScript, but could be easily adjusted for plain JavaScript.

Related

How do you override default browser styling for HTML5 input validation while retaining the default styling behavior?

I'm creating an address form for my web application and am having trouble figuring out the styling rules for HTML5 form validation with the required attribute. The examples and behavior described below are using Firefox.
The HTML for the first input field of the form looks like this:
<label for="addressLine1" class="form__label">
Address Line 1
</label>
<input type="text" required aria-required="true" class="form__input-text" id="addressLine1"/>
Without any custom styling the input behaves like this:
When the page loads, the input field displays the default styling for a text input
If I try to submit the form with the required input blank, the browser adds a red border (or shadow?) to the input
I want to retain this behavior, where the input displays some default styling on load, and only displays "invalid" styling if the user tries to submit the form with any required fields blank (or otherwise invalid). But I can't find a straight answer as to what attributes/pseudo classes I need to modify to change the styling while retaining this behavior. If I use the :invalid pseudo class, I get this behavior:
On load, the input already has my "invalid" styling, because the field is blank
If I try to submit the form with the field blank, the browser adds the red border/shadow on top of my "invalid" styling
I can only get my default/valid styling to appear by entering valid data into the input
How do you retain the default behavior (default styling on load, invalid styling on invalid submission) with custom styles, and can it be done with just CSS or do I have to add some JS functionality?
Alright so after reading over the CSS Pseudo Class docs on MDN, it doesn't look like there is any combination of pseudo classes you can string together to model the various states that make this behavior work correctly. So after playing around a bit and looking over the Bootstrap validation link Alex Schaeffer suggested, but deciding I didn't want to add extra dependencies/style sheets I didn't really need, here's the solution I came up with that adds minimal extra CSS and JavaScript.
First off, the red border was, indeed, a box shadow, so I was able to override that just by adding this to my (S)CSS:
.form__input-text {
/* default input styling goes here */
box-shadow: none;
}
Next, I added a bit of state to my component to keep track of whether or not the form has been validated yet. I'm using Svelte, so this was as simple as adding a boolean variable inside the component's <script> tag like so:
let wasValidated = false;
Then I added a conditional class to my HTML/JSX. If you're using another framework or jQuery/vanilla JS, you might need to explicitly do this with a function wired to an event handler, but in Svelte I just need to change my markup to this:
<label for="addressLine1" class="form__label">
Address Line 1
</label>
<input
type="text"
required aria-required="true"
class="form__input-text"
class:wasValidated="{wasValidated}"
id="addressLine1"
/>
All the class:wasValidated="{wasValidated}" bit is doing is conditionally adding a .wasValidated class to that input element if/when the wasValidated variable is truthy.
Then, back in my (S)CSS I added the following to apply my "invalid" styling (which at this point just changes to border color to a shade of red) only when the form had been validated at least once, and only to invalid elements:
input.wasValidated:invalid {
border-color: $red;
}
Then I wired a simple onClick function to the submit button that changes the wasValidated variable to true when the button is clicked:
HTML/JSX
<button on:click|preventDefault={onClick} class="form__submit-button" type="submit">
Search
</button>
JS
const onClick = e => {
wasValidated = true;
};
The function needs to be wired to a click event and not a submit event, because the submit event is never triggered if the form fails validation.
So now, when the page first loads, all the form inputs display the default styling, regardless of validity, because wasValidated is set to false. Then, when the submit button is clicked wasValidated is toggled to true, the .wasValidated class is applied to any required elements, which, if they are invalid, then display the "invalid" styling. Otherwise, if the form is successfully submitted, the onSubmit function wired to the form handles things from there.
Edit: As it turns out, in Svelte, you can unbind event handlers after the first time the event fires. So my markup for the submit button now looks like this:
<button on:click|preventDefault|once={onClick} class="form__submit-button" type="submit">
Search
</button>
Adding the |once modifier to on:click unbinds the onClick function the first time the button is clicked, so the function doesn't keep firing unnecessarily if the user attempts to submit invalid data multiple times.
How do you retain the default behavior (default styling on load,
invalid styling on invalid submission) with custom styles, and can it
be done with just CSS or do I have to add some JS functionality?
You can achieve this effect with a very small amount of javascript (four lines).
The reason why your input is showing as invalid is because it is both empty and required.
So one 3-step approach looks like this:
Step 1: Declare the element in your HTML using the attribute required
<input type="text" required>
Step 2: Then remove that attribute via javascript immediately
const addressLine1Input = document.getElementById('addressLine1');
addressLine1Input.removeAttribute('required');
Step 3: Then, as soon as a single character is entered into the <input> use javascript a second time to add the required attribute back in again.
const setRequired = (e) => e.target.required = 'required';
addressLine1Input.addEventListener('keyup', setRequired, false);
You can test that all this is working below by adding one or several characters to the <input> and then deleting all of them.
You will see that the <input> is initially empty but does not show as invalid, then contains characters and does not show as invalid and, finally, is empty again and now does show as invalid.
Working Example:
const addressLine1Input = document.getElementById('addressLine1');
addressLine1Input.removeAttribute('required');
const setRequired = (e) => e.target.required = 'required';
addressLine1Input.addEventListener('keyup', setRequired, false);
input:invalid {
background-color: rgba(255, 0, 0, 0.3);
border: 2px solid rgba(255, 0, 0, 0.5);
}
<form>
<label for="addressLine1" class="form__label">Address Line 1</label>
<input type="text" name="addressLine1" id="addressLine1" class="form__input-text" placeholder="Enter address here..." aria-required="true" required>
</form>
I don't think that this is possible with pure CSS, you also need some JavaScript
CSS
#addressLine1{
border: none;
background: none;
outline: none;
border-bottom: 1px solid black;
}
JS
document.getElementById('form_id').addEventListener('submit',function(e){
let address = document.getElementById('addressLine1').value
if(address == ""){
e.preventDefault()
address.style.borderBottomColor = "red";
}else{
address.style.borderBottomColor = "black";
}
})
The easiest way to accomplish unified styling across all browsers would be to use Bootstrap Validation https://getbootstrap.com/docs/4.0/components/forms/?#validation.

Can't set focus on an input box programmatically in Angular

I'm trying to follow a suggestion and have set a marker on the input control in my component like this.
<span (click)="onEditClick()"
[class.hidden]="editing">{{value}}</span>
<input #input
value="{{value}}"
[class.hidden]="!editing">
I noticed that clicking the span hides it and presents the input but an additional click is required to make the input control actually focused for editing. I tried to focusify it as follows.
#ViewChild("input") input: ElementRef;
onEditClick() {
this.editing = true;
this.input.nativeElement.focus();
}
It doesn't work, so I verified that the native element is set and corresponds to what I expect. It did. And since there are no errors in the console, I'm a bit stuck not knowing how to diagnose it further.
I suspect that I'm missing something rather basic that can easily be inferred from the provided description.
The problem is that the input element is still hidden when you try to set focus on it. To make sure that the input element has become visible after setting the editing property, force change detection by calling ChangeDetectorRef.detectChanges():
onEditClick() {
this.editing = true;
this.changeDetectorRef.detectChanges();
this.input.nativeElement.focus();
}
See this stackblitz for a demo.

onFocus bubble in React

jsfiddle : https://jsfiddle.net/leiming/5e6rtgwd/
class Sample extends React.Component {
onInputFocus(event) {
console.log('react input focus')
}
onSpanFocus(event) {
console.log('react span focus')
// event.stopPropagation()
}
render() {
return ( <span onFocus = {this.onSpanFocus}>
react input: <input type="text"
onFocus = {this.onInputFocus} />
</span> )
}
}
ReactDOM.render( < Sample / > ,
document.getElementById('container')
);
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<div>
<span onfocus="(function(){console.log('normal span')})()">
normal input:<input type="text" onfocus="(function(){console.log('normal input focus')})()">
</span>
</div>
jsfiddle : https://jsfiddle.net/leiming/5e6rtgwd/
Using React, onFocus in <input/> will bubble which is not same as usual HTML5.
Could anyone give me the refer doc why focus bubbles with React?
focus events do not bubble, so you're correct that the behavior in React differs from that of the DOM. The DOM has a focusin event that does bubble; here's a demonstration:
<div>
<span onfocus="(function(){console.log('span focus')})()">
onfocus: <input type="text"
onfocus="(function(){console.log('input focus')})()">
</span>
</div>
<div>
<span onfocusin="(function(){console.log('span focusin')})()">
onfocusin: <input type="text"
onfocusin="(function(){console.log('input focusin')})()">
</span>
</div>
Looking through the React source code, it seems this was intentional; the code checks for whether or not the browser supports the focus event with capturing, and implements it via the focus event with ReactEventListener.trapCapturedEvent instead of ReactEventListener.trapBubbledEvent. This is necessary because React implements its synthetic event system using event delegation, and so needs to use either capturing or bubbling for all its event handling. The article linked to in the comment explains how this works:
The problem is that these events do not bubble up. A focus or blur event on a link fires only on the link itself, and not on any ancestor element of the link.
This is an ancient rule. A few events, most notably focus, blur, and change, do not bubble up the document tree. The exact reasons for this have been lost in the mist of history, but part of the cause is that these events just don't make sense on some elements. The user cannot focus on or change a random paragraph in any way, and therefore these events are just not available on these HTML elements. In addition, they do not bubble up.
...
Except when you use event capturing.
...
One of the most curious conclusions of my event research is that when you define event handlers in the capturing phase the browser executes any and all event handlers set on ancestors of the event target whether the given event makes sense on these elements or not.
It seems pretty likely that the React team decided to simply make the event always bubble (which, to be honest, is what I expected from the DOM spec as well until I read your question). The browser implementations don't seem to be consistent; one issue comment mentions that focus events bubble in Firefox, but I was not able to reproduce that on a recent version. However, using an onfocusin attribute or using addEventListener("focusin", ...) also didn't work in FF. So it's possible that this was simply an attempt at normalizing the events across browsers.
All that said, it does seem there is perhaps a bug where the .bubbles property on a SyntheticFocusEvent is false instead of true.

Why is a custom angular directive not disabled with ng-disabled set to true

I have been playing around with ngAria and ngDisabled in AngularJS using the example given here .I modified the custom-checkbox directive in the example to set ng-disabled= true in the controller , that further sets aria-disabled=true as seen in the plunker output here.
<some-checkbox role="checkbox" ng-model="checked" ng-class="{active: checked}" ng-disabled="isDisabled" ng-click="toggleCheckbox()" aria-label="Custom Checkbox" show-attrs>
var app = angular.module('ngAria_ngModelExample', ['ngAria'])
.controller('formsController', function($scope){
$scope.checked = false;
$scope.isDisabled=true;
$scope.toggleCheckbox = function(){
$scope.checked = !$scope.checked;
}
})...
But with ng-disabled=true and aria-disabled=true this does not disable the "Custom Checkbox" as seen in the plunker output.
As per the documentation here and several examples on stackoverflow, the "disabled" attribute works only for buttons, input and text area. For custom directives (like the one above), ngDisabled is the way to go. But it does not seem to work for the above example. Any help here is appreciated.
The disabled attribute is only valid for certain elements such as button, input and textarea
ngDisabled adds or removes the disabled attribute to your element. I suggest you watch the disabled expression in your custom directive, and add / remove a class to disable your component.
If you're creating your own component that you want to have support for ng-disabled, then you can add this inside $onInit after injecting $attrs and $parse:
// Watch ng-disabled
this.$scope.$watch(
() => {
let value = this.$attrs.ngDisabled;
// Evaluate ng-disabled expression on parent scope
let evaluated = this.$scope.$parent.$eval(value);
return evaluated;
},
(disabled) => {
this.disabled = disabled;
}
);
As with all ARIA controls, the browser does not give you any "behavior" for free. What the addition of roles like "button" does is it instructs the browser/screen-reader what to do with announcements and what to do with keyboard events. What I mean by "what to do with keyboard events", this means "switch to-or-from forms mode automatically when the element receives focus".
This means that you need to:
Implement event handlers for keyboard and mouse/touch commands,
Implement the visual styling to convey the state of the component
(e.g. disabled, enabled or selected, not selected etc.), and
Implement the interpretation of the state (so disable the keyboard and
touch/mouse handling when the state is disabled)

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

When a web form is written to the browser, the browsers remembers what the initial values are of a text INPUT box. ie. when it receives HTML like this:
<input type="text" value="something">
The browser remembers "something" as the initial/default value. When the user starts typing over it, then hits ESC, the browser reverts the field to the initial value (or blank if it was initially blank of course).
However, when creating a text input box programatically, hitting ESC always seems to blank the box, even if I create it with a default value like so:
$('<input type="text" value="something">')
The browser doesn't count this as a default value and doesn't revert to it when hitting ESC. So my question is, is there a way to create a text box in code and somehow assign it a default value, so the ESC key works as if the browser received it in the HTML document?
You might looking for the placeholder attribute which will display a grey text in the input field while empty.
From Mozilla Developer Network:
A hint to the user of what can be entered in the control . The
placeholder text must not contain carriage returns or line-feeds. This
attribute applies when the value of the type attribute is text,
search, tel, url or email; otherwise it is ignored.
However as it's a fairly 'new' tag (from the HTML5 specification afaik) you might want to to browser testing to make sure your target audience is fine with this solution.
(If not tell tell them to upgrade browser 'cause this tag works like a charm ;o) )
And finally a mini-fiddle to see it directly in action: http://jsfiddle.net/LnU9t/
Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected: http://jsfiddle.net/3GLwE/
This esc behavior is IE only by the way. Instead of using jQuery use good old javascript for creating the element and it works.
var element = document.createElement('input');
element.type = 'text';
element.value = 100;
document.getElementsByTagName('body')[0].appendChild(element);
http://jsfiddle.net/gGrf9/
If you want to extend this functionality to other browsers then I would use jQuery's data object to store the default. Then set it when user presses escape.
//store default value for all elements on page. set new default on blur
$('input').each( function() {
$(this).data('default', $(this).val());
$(this).blur( function() { $(this).data('default', $(this).val()); });
});
$('input').keyup( function(e) {
if (e.keyCode == 27) { $(this).val($(this).data('default')); }
});
If the question is: "Is it possible to add value on ESC" than the answer is yes. You can do something like that. For example with use of jQuery it would look like below.
HTML
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<input type="text" value="default!" id="myInput" />
JavaScript
$(document).ready(function (){
$('#myInput').keyup(function(event) {
// 27 is key code of ESC
if (event.keyCode == 27) {
$('#myInput').val('default!');
// Loose focus on input field
$('#myInput').blur();
}
});
});
Working source can be found here: http://jsfiddle.net/S3N5H/1/
Please let me know if you meant something different, I can adjust the code later.
See the defaultValue property of a text input, it's also used when you reset the form by clicking an <input type="reset"/> button (http://www.w3schools.com/jsref/prop_text_defaultvalue.asp )
btw, defaultValue and placeholder text are different concepts, you need to see which one better fits your needs