onKeyUp called when second button pressed - javascript

I'm making a custom input field which should support subscript. When the user presses the down arrow + a number, then the number should be in subscript. I appended a onKeyDown and onKeyUp event listener to a content editable paragraph. Unfortunately the onKeyUp gets called when the user presses the number, which results in adding the number twice (once in subscript and once normal). How can I solve this problem?
function keyDown(event) {
var code = event.keyCode;
if (code === 40) {
option = 0;
}
}
function keyUp(event) {
var code = event.keyCode;
if (code === 40 || code === 38) {
option = -1;
}
console.log("release");
}
The onKeyPressed is not an option since this does not recognize the arrow keys in all browsers. Is there a native solution (without jQuery)?

What I usually do is to push the keyCodes into an Array on keyDown and .splice() it on keyUp.
All you have to do now is to check (probably against a pre-defined map) if the key states you desire are available in that Array.

As long as your text field has focus, any numeral key you press will be added to it in addition to whatever your keyup or keydown listeners add to it. Maybe you should take away focus from the text field on keydown if the key you are pressing is the down key and add focus back again after the keyup event has fired.
/* Keep track of the down key. */
var down=false;
/* Get the input text field. */
var input=document.getElementById("input");
input.addEventListener("keydown",keyDown);
input.addEventListener("keyup",keyUp);
/* Give focus to input. I'm not sure if this is the right way to do it, I haven't tested this code, but I know there's a way to give focus to elements and it sort of looks like this. */
input.focus();
function keyDown(event_){
switch(event_.keyCode){
case 40:
/* Once again, not sure how to unfocus, but I know you can. */
input.unfocus();
down=true;
break;
}
}
function keyUp(event_){
switch(event_.keyCode){
case 40:
/* Give focus back to input after the keyup event has fired. */
input.focus();
down=false;
break;
}
if (down){
input.value+=//The subscript version of whatever key you pressed.
}
}
Once again, I would just like to say that this code hasn't been tested and I'm not sure if focus() and unfocus() are real methods, but you get the idea. You want to momentarily stop the text field from accepting input while the down key is pressed so you can add your own special value to it without updating it's contents with the default response and then give focus back to the text field once the down key is no longer in use.

Related

How to use Javascript to determine where a user is typing on webpage and react accordingly

I am new to javascript, and am writing a simple bookmarklet for a webpage that has a text input section. Basically what I need is a way to execute the following-
if ( ! (text_section).onkeydown ) {
do whatever
}
I need to ignore key-events when the user is typing inside an input field but otherwise trigger key-events for the entire page whenever the user presses a key. I do know that onkeydown is an event listener/handler I'm just trying to explain what I need to do more accurately.
Use an id for your text-section, for example "myTextSection". Apply the addEventListener to the whole document. If the target is anything else, than the textfield, do whatever:
document.addEventListener("keydown", (event) => {
if(event.target !== document.getElementById("myTextSection")){
//do whatever;
}
});
Note that this behaviour might be irritating for users, that navigate by keyboard (for example tab and space keys) through your page. So you might want to add another if statement checking whether the event.keyCode is alphanumeric. In this case the keyCode is in the ranges
[47-58] (for 0-9),
[64-91] (for A-Z) or
[96-123](for a-z)
You should add an event listener to the target element:
targetElement.addEventListener('keydown', (e) => {
// do something
});
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
It is also possible to use onkeydown property:
targetElement.onkeydown = (e) => {
// do something
}
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onkeydown

How to traverse the input field in the Google search result page and auto focus on it?

I want to set a shortcut to focus on the input field in the Google search result page, instead of using mouseover or mousemove Event.
How to traverse all the elements in a page to get the input field to execute focus() by using Javascript.
document.addEventListener('keydown',function(event){
var keynum;
if(window.event) // IE
{
keynum = event.keyCode;
}
else if(event.which) // Netscape/Firefox/Opera
{
keynum = event.which;
}
console.log(event.keyCode)
if(keynum==79&&event.altKey){
//get the input element in a page and execute focus()
}
});
First of all, to get the search bar element, we need to use the querySelector. After that, we need to focus on the input. Even after this, we will not see the automatic suggestions that google gives us. So, we also need to stimulate the click event. The below code will do the work -
let searchBar = document.querySelector("input[type=text]");
searchBar.focus();
searchbar.click();

Capture keycode on input's with same class

I have a page with many text input's. All input's share the same class for many reasons.
Now I am trying to capture a the ESC button when an input is focused and alert if the input has value or not.
Now this logically works only for the first field. After the first field, since all input's share the same class, when I press ESC button it gives you the value of the very first input.
So how can I say that I'm talking for the second, fifth or whatever input I am pressing ESC on.
Here is an example: http://jsfiddle.net/Y5e9W/
The first input works fine, the second input thought; when you press ESC it gives you the values of the first.
You should be able to bind the keyup event to the elements with your class, rather than the document. Then this will refer to the element with focus:
$(".gp").keyup(function(e) {
if(e.which === 27) {
if(this.value.length > 0) {
//Has a value!
}
else {
//Empty!
}
}
});
Here's an updated fiddle. Note that I've used the which property of the event object, which jQuery exposes to deal with browser differences between keyCode and charCode.
Update based on comments
If you do need to handle this at the document level, you can use the has method to narrow down your selection of .gp elements to the one which has focus:
if (gj.has(":focus").val() != 0) { //...
Here's another fiddle.
You could do -
$(".gp").keyup(function (e) {
if ($(this).is(":focus") && (e.keyCode == 27)) {
if ($(this).val() != 0){
alert('full');
$(this).val('');
}else{
alert('empty');}
}
});
Which will only respond to the keyup event of elements with the 'gp' class, you can then use this to access the relevant element.
Demo - http://jsfiddle.net/uqS72/2/

HTML Select: Eliminating browser Delay on keypress-to-change?

Consider the following HTML:
<select>
<option>Aardvark</option>
<option>Buffalo</option>
<option>Camel</option>
<option>X-ray Fish</option>
<option>Yak</option>
<option>Zebra</option>
</select>
In most browsers, when the select element has focus, pressing a key will change the selected value to the next option that begins with the character typed. For instance, pressing 'B' on the keyboard while the <select> element above has focus changes the selected value to "Buffalo". Pressing 'Z' after that will change the value to "Zebra".
But I just discovered that, at least in Firefox 6 and Safari 5 on my PC, there is a delay before I can press-to-select the next value. In the specific example above, if I press "B" and then press "Z" less than a second later, nothing appears to happen.
However, in further testing (with jQuery) I discovered that the Javascript events 'keydown', 'keyup', and 'keypress' ARE all fired as you'd expect, no matter how rapidly you press the keys. The browsers themselves just don't switch the selected option until a certain period of time has passed.
Is there any way to get around this?
It seems to be possible with cloning. It's a really dirty hack but works just fine in Chrome: http://jsfiddle.net/pimvdb/v6qy8/2/.
$('select').keyup(function() {
var newSelect = $(this).clone(true).val($(this).val());
$(this).replaceWith(newSelect);
newSelect.focus();
});
I did it by interrupting the keyevent and placing a preventDefault() at the top of the function. I use the Enter key to break the delay and submit what I've typed already.
if (eventinfo.keyCode == 13) {
eventinfo.preventDefault();
var search = document.getElementById("searchtag");
var value = search.value;
mainPage.searchAdd(value).done(
function () {
search.value = "";
search.focus();
}
);
}

How do write a JavaScript function that allows for non-editable textbox?

I need to have an input textbox in which I can click and the cursor starts blinking but the user cannot change any text inside it.
I tried using "readonly" or "disabled" attributes, but they do not allow the cursor to be inside the textbox. So, I was thinking of a solution to implement in JavaScript on a normal textbox. Is there a plugin that already do this? How do I implement this?
EDIT: Thanks for all the answers, but I wanted to make the textarea/input type text as uneditable but selectable at the same time. Pressing Ctrl + A inside the textbox doesn't work. Is it possible to get the changed value and the old value and compare them and then return false if the values are different, but in all other cases return true so that the Ctrl + A, Shift + end, etc. combinations work?
Something like this:
<textarea onkeydown="javascript:return false;"></textarea>
would do the trick. (jsfiddle)
You can also do that at runtime if you want to:
<textarea class="readonly"></textarea>
with
$(".readonly").keydown(function() false);
The onkeydown callback captures keystroke events and cancels them using return false;.
Depending on what you are trying to do, you may want to prevent other kind of events, since it is still possible to change the contents with the mouse, for instance.
Your callback function can accept or cancel events depending of the kind of keystroke. For example, to enable only ctrl-a and ctrl-c (with jQuery):
function keydown(e) {
if(!e.ctrlKey) return false; // Cancel non ctrl-modified keystrokes
if(e.keyCode == 65) return true;// 65 = 'a'
if(e.keyCode == 67) return true;// 67 = 'c'
return false;
}
$(function(){
$("inputSelector").keydown(function(){ return false; });
});
You cannot rely on disabling a <textarea> as a user input, as it's trivial to remove any sort of HTML or javascript disabling with firebug, or other tools. Remember that forms aren't limited to the fields you give them, anyone can submit any data to a page.
Disabled inputs are not submitted with a form anyway, bearing that in mind my advice would be to not use a textarea and just print it out.

Categories