I have a simple display project and want to cut out the mouse from the equation, the page only has one field (a search field) and I want the browser to be locked into to the field remove the need for a mouse while keeping it user friend for those who don't know how to maneuver without a mouse.
Can it be done with jQuery/Javascript? I don't really know what im search for besides it may have something to do with tab indexing.
Thanks,
Arthur
Since Gaby hasn't edited, I'll go ahead and write up the solution. Some of the credit for the code goes to Gaby and Andy E.
$(document).ready(function(){
var el = $(':text:eq(0)');
el.focus();
el.blur(function(){
setTimeout(function() { el.focus(); },0);
});
});
if you mean that you want the field item to be focused (so that the user can start typing in it right away) then
$(document).ready(function(){
$(':text:eq(0)').focus();
});
this will put the focus inside the first input box it will find in the page..
(the :eq(0) can be omitted if you only have one input box ..)
Related
I have been doing research on this simple sounding issue for a couple of days and I have not seen any result.
In a nutshell my problem is as follows: I would like to select text in a some input field, move focus to another field (or generally speaking some other element), but not lose my selected text.
Such a situation could correspond to a use-case in which I select text in a field, right-click and display a custom popup menu, but do not wish to lose focus of selected text, because I want to do some operations on the previously selected text.
A small code test sample would be (for my initial simple scenario - here I am forcing text selection when the second input field gains focus):
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<input type="text" id="text1" size="20" value="Test1"/>
<input type="text" id="text2" size="20" value="Test2"/>
<script>
$('#text2').focus( function (evt) {
var target = $('#text1')[0];
target.select();
console.log('active/focused element: ' + document.activeElement.id);
});
</script>
</body>
</html>
I have been searching SO and web for a solution to this and have not seen much if any help.
I am not sure this is even really possible (due to the link between blur and selection lost and focus and selection). I have seen a style property called preventDeselect, in another SO answer - this does not work and I have not even such documentation or browser support for this.
I am quite struggling with this and would appreciate some help: even saying I can't do this at all or maybe some ways to go.
UPDATE:
Just for the record, my user scenario, which refers to text selection and context menu, is a common one (it slipped my mind to mention): just select some text in this page (or in an input type field) and right click to get the browser's default context menu - my scenario is different in that i want to use a custom menu, but with similar behavior to the browser's context menu - which normally allows to select some text, cut/copy the selection, navigate within the context menu without losing the selected text. So I think it should be possible somehow :) to do all these things with a context menu and still have your selection.
Attempting to answer this part of your question:
Such a situation could correspond to a use-case in which I select text
in a field, right-click and display a custom popup menu, but do not
wish to lose focus of selected text, because I want to do some
operations on the previously selected text.
For this use-case, I created a quick fiddle: http://jsfiddle.net/4XE9a/1/
Note: Am using the same getSelection function from #David's answer.
If you select any text and then right-click on the input, a custom popup menu appears. Click "option 1". You will find that the selection is not lost even though the focus has shifted to that anchor tag.
However, for the second part of your question regarding focus shifting to another textbox, #David's answer suffices.
Update: (after your comments)
Please see this updated fiddle: http://jsfiddle.net/783mA/1/
Now, when you select some text and right-click on the input it will show the custom popup menu with three options. Use tab to navigate and press space or click on the highlighted option. (Due to paucity of time I could not implement up/down arrow keys, but the concept remains the same)
This demonstrates your question in the comment that the selection is still not lost while navigating the menu.
Note: You are wanting to visually keep the selection highlight and not lose the selection while clicking anywhere else. Please note that this is not possible because text selection behavior is OS implemented. Browser, html etc do not play a role here. The text selection is lost as soon as you click anywhere outside the context of selection. This is because the system starts expecting a new selection as soon as you click anywhere outside. However, controls without text surface are exempt. Button, scrollbar arrows etc will not cause selection to lose.
To view this behaviour, in the fiddle, select some text and then click any dropdown on the left pane. The text selection is not lost, even visually for that matter.
This is why in the new fiddle above, I purposely used buttons to demonstrate.
You can save each selection in an interval, then retrieve it when you like. Here is an example that pulls the selection when the input has focus and clears the interval on blur:
function getSelection(elm) {
var start = elm.selectionStart;
var end = elm.selectionEnd;
return elm.value.substring(start, end);
}
$('input').focus(function() {
var self = this;
$(this).data('interval', setInterval(function() {
$(self).data('selection', getSelection(self));
},20));
}).blur(function() {
clearInterval($(this).data('interval'));
});
Now you can stuff like:
$('#text2').focus(function() {
console.log('selection in #text1 was: '+$('#text1').data('selection'));
});
Demo: http://jsfiddle.net/qCCY5/
I am making a terminal window in HTML/JavaScript and am using a textarea for input. I would like to prevent sections of the text in the textarea from being deleted. For example, if I had the text in the textarea "C:\>Random Code" I would like to prevent the user deleting the "C:\>" text. Is this possible using javascript?
Assuming jQuery, this script will listen for keystrokes, and if any of the required text can't be found (ie: user tries to delete it) it will add itself right back in there:
var requiredText = 'C:>';
$('textarea').on('input',function() {
if (String($(this).val()).indexOf(requiredText) == -1) {
$(this).val(requiredText);
}
}
You cannot make a section of textarea uneditable (only the whole control).
You can use various JavaScript trickery (listening to keypress events and cancelling event using event.preventDefault if the user wants to do something that you do not want to allow)
Another solution is to, instead of having an undeletable section of the input, to automatically append (or prepend ) a predefined string to the user input (and conveneintly display it for the user in some way).
Update:
So, my solution would look like this:
var requiredText = 'C:>';
$('textarea').on('keyup',function(event) {
if (GetSelectionStart(this) < requiredText.length){
event.preventDefault();
event.stopPropagation();
}
}
Where GetSelectionStart is a function that tells the beginning of the selected text (or caret position, if no text range is selected). For some possible implementations, see e. g. Caret position in textarea, in characters from the start
This function assumes that requiredText is always at the beginning of the string. But of course, it can be adapted for more complex scenarios.
I have password field on the page, where password shown is masked but I wanted users to copy the password in its clear text form and be able to paste it somewhere in another website.
I followed this article Mask text, but still allow users to copy it and created another input[type=text] field with opacity 0.001 and made this fields adjustment such that it overlaps with the password field
Now when users tries to copy password from password field, they are actually copying from another input field value whose opacity is very low.
But now I want to make users experience good when selecting password, because currently when copying users dont know whether the value is getting copied or not because they copying from another input field which is overlapped with another.
So I am in search of any css/jquery trick which will highlight the text(password asterisk) present behind the actual field(with opacity 0.001). So that users at-least come to know that their values is actually getting copied.
Thanks,
Dean
Are you really sure you or your users need this or is this meant as a convenience feature? No password field that I have seen allows to copy. Unless advertised, the number of people using this feature will be close to zero. Maybe a “copy password” link with ZeroClipboard is a better solution?
Anyway, here’s the best I could come up with. It uses jQuery-textrange plugin to handle text selection across browsers. It needs rather recent versions, too. jsfiddle demo.
The main idea is to make the low-opacity field ignore mouse events, so the user can select text in the password field normally. The advantage is that we don’t need to handle selection rendering at all. This can be achieved by CSS:
#account-password-hide { pointer-events: none; }
Next, once the user finishes a selection we get the selection position and select the same portion in the low-opacity field. Unfortunately, this will clear the selection in the password field.
$("#account_password").select(function () {
console.log("moving selection to hidden field");
var pos = $("#account_password").textrange();
$('#account-password-hide').textrange('set', pos.start, pos.end);
$('#account-password-hide').css("pointer-events", "auto");
});
CTRL+C works now, and so does right click → copy because we set pointer-events: auto. If it were still none, then a right click would go into the actual password field, preventing the copy operation.
Lastly we need to reset the pointer-events so that the next click goes into the correct field again:
function reset() {
$('#account-password-hide').css("pointer-events", "none");
}
$('#account-password-hide').mousedown(function (evt) {
// allow right clicks
if (evt.which !== 3) {
reset();
}
});
$('#account-password-hide').mouseup(function () {
reset();
});
$('#account-password-hide').blur(function () {
reset();
});
As far as I can tell, this basically works.
In order to keep the selection on focus change, you’d have to create an additional element that holds the same characters as the password field (i.e. same look as the asteriks/dots in the password field). Then you can highlight the selected characters using CSS system colors. Getting z-index and opacity for each of them right is going to take some testing though.
I have trapped the cut event (jquery) on a textbox. What I want is to get the text on the textbox during the cut event is triggered.
I've tried accessing the data the user cut via evt.originalEvent.clipboardData.getData('text') but returns undefined.
My goal is to know if the user cut all the text (textbox is now empty) or not.
Thanks in advance
You can setTimeout with a duration of 0, which schedules a function for immediate execution. The nice thing is that the function will execute once the text has already been cut, so you can check then if your textarea is empty (which would mean that the user has cut all the text):
var ta = $('#YOUR_TEXTAREA');
ta.bind('cut', function() {
setTimeout(function(){
if (!ta.val()) {
// user cut the whole text.
}
},0);
});
You might also want to add a check before the setTimeout to test whether there is any text in the textarea before the text gets cut (if the user presses Ctrl^X without any text being selected, the cut event still triggers)
Hope I got you right:
In jQuery you could use something like this to see if a textbox is empty on every user's keyup:
var txt;
$('#textbox_ID').live('keyup', function() {
txt = $(this).val().length;
if(txt < 1) {
alert("textbox is empty");
}
});
This should work, because everytime the user releases a key and has the textbox focused, it checks if it's empty.
I would suggest looking at this, JavaScript get clipboard data on paste event (Cross browser), it is for the paste event but I'm sure you could do something similar and compare the current value to that on the clipboard, if they are exactly the same than the input would be empty, otherwise not.
I don't know what this is called so its hard to google for it.
If you have a plain html input type=text with a small width eg 20 and then type more characters than can be displayed, it shows the last characters you type. And the first ones are scrolled out of view:
This is my long text // this is the whole string
my long string // this is what is actually visible in the input box
How do I make it so that when you hit tab, the view area resets so that the start of the string is visible and the end is hidden?
my long string // this is what is visible in the input box when typing
This is my // this is what is I want to be visible in the input box after you hit tab
What do you call this, and how do you do it?
I don't know if your question has been answered, but I just felt like answering myself. You can do it by using ranges and window selection. Here, I made a JSFiddle for you.
$(document).ready(function(){
$("input").bind("keyup",function(e){
if(e.keyCode==9){
var r=document.createRange(),
gs=getSelection();
r.setStart(this,0);r.setEnd(this,0);
gs.removeAllRanges();gs.addRange(r);
}
});
$("input").bind("blur"),function(){
$(this).focus();
});
});