Whenever the tabkey is pressed without an active/focussed element, the first focussable element is selected (this is the general behaviour of the tab key. However, I dont want this in my application, since I want to focus on another element (not the first one).
I have tried setting event listeners for the tab key, but this only works if some element is already selected and not when no element is active.
Is there any way to listen to this 'initial tab event' when there are no active elements? In de code snippet you can see that the tab event only listens to the second tab, while it selects the first field after the first tab.
document.getElementById("form").addEventListener("keydown", function(e){
if(e.keyCode===9){
document.getElementById("demo").innerHTML = "Tab";
}
}
)
<div id="form">
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br><br>
<input type="submit" value="Submit">
</div>
<p id="demo"></p>
I would go with TabIndex:
Adding tabindex="0" to an element, you can then access it with your keyboard key. Adding tabindex="-1" does not give access to that alement keyboard-based (however, you can access it to gain focus programmatically - with .focus() or with a click for example).
So if your keyboard-based behavior doesn't work because nothing is selected, force you application to select an element on init (for example you element with a tabindex of -1):
// By using a tabindex of -1, the element won't be focusable via keyboard
// but, we can programmatically focus it.
.attr( "tabindex", "-1" )
.focus()
Related
I have several html input controls on a page and a search button. When user is outside the input controls, ( ie focus is not inside the input control) and if user press enter, i want to trigger click event of search button. The search button is not a Submit button and it is not inside a form
<input type="text" id="input1" />
<input type="checkbox" id="input2" />
<input type="text" class="autocomplete" id="input3" />
<button type="button" id="btnSearch">Search</button>
currently I am doing this
$(document).keypress(function (event) {
if (event.keyCode === 13) {
$("#btnSearch").click();
}
})
However, the above code triggers click event every time user clicks enter.
Some of the input controls I have are custom autocomplete controls. Auto complete control shows multiple options as soon user starts typing something. Then user can select the option by using mouse or by pressing enter.
I don't want to trigger the click event of a search button when user press enter to select an option.
Just make sure that the autocomplete element isn't the source of the enter press. From the demo you give in your question, this will work. However, if it is slightly different in your use case, you may need to adjust the class name or selector to make sure it is preventing the correct target element
$(document).keypress(function (event) {
if (event.keyCode === 13 && !$(event.target).hasClass("autocomplete")) {
$("#btnSearch").click();
alert('btnSearchClick');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1" />
<input type="checkbox" id="input2" />
<input type="text" class="autocomplete" id="input3" />
<button type="button" id="btnSearch">Search</button>
Alternatively, since events propagate out, if you can prevent the propagation of the autocomplete event in whichever library you are using, that may work as well.
Hello I am working on a simple form that also uses place-holder text. I am implementing this behaviour with JQuery and not html attributes, mainly because the place-holder input also shows error messages to the user which need to be styled differently than plain place-holder text.
Right now the form behaves like this.
Clicking on the input hides the the place-holder input and sets focus on the main input field.
If the user has entered data then the place-holder does not show up.
Now this is all fine, but when the user presses the TAB key to change focus, none of the above happens.
Here is the relevant JQuery code and the HTML:
$("#plh_username").click(function(){
$(this).hide();
$("#username").focus();
});
$('body').click(function(e){
var target = $(e.target);
if(!target.is('#plh_username')) {
if ( $("#username").val() == "" ){
$("#plh_username").show();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="input" id="plh_username" class="inp_placeholder" value="Username" />
<input type="text" name="username" id="username" value="" />
How can I achieve the same effect when the user selects an input field without actually clicking on one?
You could try using .focus() and .focusout() instead of .click().
$("#plh_username").focus(function(){
$(this).hide();
$("#username").focus();
});
$('#username').focusout(function(){
if ($(this).val() === ""){
$("#plh_username").show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="input" id="plh_username" class="inp_placeholder" value="Username" />
<input type="text" name="username" id="username" value="" />
<input value="Press tab or shift+tab" />
Quote from the documentation:
Elements with focus are usually highlighted in some way by the
browser, for example with a dotted line surrounding the element. The
focus is used to determine which element is the first to receive
keyboard-related events.
Dont use .click(). Use .focus().
I think you are looking for onfocus event. This event triggers when a control gains the focus.
$("#plh_username").focus( function(){
alert("focus")
});
for example see http://jsfiddle.net/wb2vef0g/
So, for example, here's a script:
<!-- Random content above this comment -->
<input type="text" tabindex="1" />
<input type="text" tabindex="2" />
<input type="text" tabindex="3" />
<input type="text" tabindex="4" />
<input type="text" tabindex="5" />
<input type="text" tabindex="6" />
<!-- Nothing underneath this comment -->
So, when the user presses tab and goes through the six textboxes, reaches the last one and then presses tab, it would go to the content above the first comment, right? Well, how do I make it start from tabindex="1" again?
Unfortunately, you can't do that without javascript. You can listen to a TAB (and make sure it's not SHIFT+TAB) key press on your last element and manually set the focus to your first element inside the handler. However, binding this logic to keyboard events (i.e. specific input method) is not universal and may not work when using:
A mobile browser
Some other entertainment device (smart tv, gaming console, etc. - they typically use a D-Pad for jumping between focusable elements)
An accessibility service
I suggest a more universal approach which is agnostic of how the focus is changed.
The idea is that you surround your form elements (where you want to create a "tabindex loop") with special "focus guard" elements that are focusable too (they have a tabindex assigned). Here is your modified HTML:
<p>Some sample content here...</p>
<p>Like, another <input type="text" value="input" /> element or a <button>button</button>...</p>
<!-- Random content above this comment -->
<!-- Special "focus guard" elements around your
if you manually set tabindex for your form elements, you should set tabindex for the focus guards as well -->
<div class="focusguard" id="focusguard-1" tabindex="1"></div>
<input id="firstInput" type="text" tabindex="2" class="autofocus" />
<input type="text" tabindex="3" />
<input type="text" tabindex="4" />
<input type="text" tabindex="5" />
<input type="text" tabindex="6" />
<input id="lastInput" type="text" tabindex="7" />
<!-- focus guard in the end of the form -->
<div class="focusguard" id="focusguard-2" tabindex="8"></div>
<!-- Nothing underneath this comment -->
Now you just listen to focus events on those guard elements and manually change focus to the appropriate field (jQuery used for the sake of simplicity):
$('#focusguard-2').on('focus', function() {
// "last" focus guard got focus: set focus to the first field
$('#firstInput').focus();
});
$('#focusguard-1').on('focus', function() {
// "first" focus guard got focus: set focus to the last field
$('#lastInput').focus();
});
As you see, I also made sure that we snap back to the last input when the focus moves backwards from the first input (e.g. SHIFT+TAB on the first input). Live example
Note that the focus guards are assigned a tabindex value too to make sure they are focused immediately before/after your input fields. If you don't manually set tabindex to your inputs, then both focus guards can just have tabindex="0" assigned.
Of course you can make this all work in a dynamic environment as well, when your form is generated dynamically. Just figure out your focusable elements (less trivial task) and surround them with the same focus guards.
Hope that helps, let me know if you have any issues.
UPDATE
As nbro pointed out, the above implementation has the unwanted effect of selecting the last element if one hits TAB after the page loads (as this would focus the first focusable element which is #focusguard-1, and that would trigger focusing the last input. To mitigate that, you can specify which element you want initially focused and focus it with another little piece of JavaScript:
$(function() { // can replace the onload function with any other even like showing of a dialog
$('.autofocus').focus();
})
With this, just set the autofocus class on whatever element you want, and it'll be focused on page load (or any other event you listen to).
Here my solution where you no need any other elements. As you can see elements will be looping inside <form> elements.
$('form').each(function(){
var list = $(this).find('*[tabindex]').sort(function(a,b){ return a.tabIndex < b.tabIndex ? -1 : 1; }),
first = list.first();
list.last().on('keydown', function(e){
if( e.keyCode === 9 ) {
first.focus();
return false;
}
});
});
Here is my solution, considering the first input has the "autofocus" attribute set:
Add this after your form element (with HTML5 it can be any tag):
<div tabindex="6" onFocus="document.querySelector('[autofocus]').focus()"></div>
Yes, after tabbing through the inputs it will jump on suitable elements that do not have a tab order specified. But also, after tabbing all "tabbable" elements, the focus will jump "outside" your page content, onto the browser's UI elements (tabs, menus, bookmarks, etc)
I think the easiest way is to handle the keyup event on the last input and intercept TAB usage (and SHIFT+TAB for that matter)
I wd suggest you to increase your tabindex ie. >100
and also give the tabIndex to your "content" container div
please note that your content container must have tabindex less than input boxes for ex.99 .
when you press tab on last input box manually set focus on your content div using javascript (you can use keypress handlers for tab key)
document.getElementById("content").focus();
you must giv tabindex to your "content" to set focus to it.
now if you press tab focus will automatically shift to first input box.
hope this will help.
Thank you
So I have an accordion menu that I created with Jquery:
<script>
$(document).ready(function() {
/*Accordian Script for the Request New Appraisal Panel*/
$('.accordian_item').hide();
$('.accordian_item').first().slideDown();
$('.accordian_trigger').click(function(event) {
event.preventDefault();
$(this).parent().find('.accordian_item').slideToggle();
});
});
</script>
Now, I want to be able to dynamically append extra accordion items to the accordion box, which I have done like this:
<script>
$('#add_contact_btn').click(function(event) {
event.preventDefault();
var large = '<div class="accordian_container"><h4>Co-Borrower Information</h4><hr/><div class="accordian_item"><label> First Name</label><br/><input type="text"/><br/><label>Middle Name</label><br/><input type="text"/><br/><label>Last Name</label><br/><input type="text" /><br/><label>Home Number</label><br/><input type="text"/><br><label>Work Number</label><br/><input type="text"/><br><label>Cell Number</label><br/><input type="text"/><br></div></div>';
$('#accordion_container_box').append(large);
});
</script>
This works perfect, except the dynamically generated items don't collaps when you click on the collapse button. The existing accordion items still work. For some reason it seems like Jquery wont trigger for dynamically created links. Any ideas how I can correct this?
BTW, here is the basic HTML structure:
<div id="accordion_container_box">
<div class="accordian_container">
<h4>Borrower's Information</h4>
<hr/>
<div class="accordian_item">
<label> First Name</label><br/>
<input type="text"/><br/>
<label>Middle Name</label><br/>
<input type="text"/><br/>
<label>Last Name</label><br/>
<input type="text" /><br/>
<label>Home Number</label><br/>
<input type="text"/><br>
<label>Work Number</label><br/>
<input type="text"/><br>
<label>Cell Number</label><br/>
<input type="text"/><br>
</div>
</div>
<div class="accordian_container">
<h4>Co-Borrower's Information</h4>
<hr/>
<div class="accordian_item">
<label> First Name</label><br/>
<input type="text"/><br/>
<label>Middle Name</label><br/>
<input type="text"/><br/>
<label>Last Name</label><br/>
<input type="text" /><br/>
<label>Home Number</label><br/>
<input type="text"/><br>
<label>Work Number</label><br/>
<input type="text"/><br>
<label>Cell Number</label><br/>
<input type="text"/><br>
</div>
</div>
</div>
+ Additional Contact
You have to use .live('click'... on dynamically created content.
By default binding events to elements will only affect nodes that exist at the time that the bind runs. By using event delegation you can make use of the built in way that events bubble. jQuery < 1.7 did this with the delegate and live methods, jQuery 1.7 added the on method to consolidate all the event handlers in a single API.
For example you could use the following to handle all clicks on nodes with a class of accordian_trigger regardless of when they were created.
$(document).on('click', '.accordian_trigger', function() {
//whatever you need to do
});
What this will do is attach an onclick event handler to the document itself. When any click occurs in the DOM it will bubble up from the node that the event occurred on to its parent and its parent until it reaches the document. jQuery will then check whether the event occurred on a node that matches the selector passed in as the second parameter of on, in this case it will check whether the node has a class of accordian_trigger. If it does it will run the function passed in as the third parameter.
For efficiency's sake you'll likely want to replace document with a parent node that you know will contain all accordian_trigger nodes. Otherwise all clicks bubble all the way up to the document and check whether the node that was clicked on has the accordian_trigger class, which is potentially expensive, especially if you have a large DOM.
Is there a nice way to set a desktop-like tab order in a form with jquery? the form has four text inputs and two buttons; after the last button loses focus, I want the first text input to get focus and start tab order from the beginning (to 2nd tb, to 3rd tb...). I did this:
$('body').delegate('#second_button', 'blur', function() {
$('#first_input_text').focus();
});
but it only works in Opera. Chrome IE9, And Firefox do set focus on first text input but when user press tab again it goes to address bar instead of the second text input. I could set above binding to all elements in cycle but is there a more elegant solution?
You need to add a tabindex attribute to each form element - example :
<FORM action="..." method="post">
<P>
<INPUT tabindex="1" type="text" name="field1">
<INPUT tabindex="2" type="text" name="field2">
<INPUT tabindex="3" type="submit" name="submit">
</P>
</FORM>
Documentation here