Detect text-input elements in javascript - javascript

In JavaScript, I would like to detect some key presses. But I want to ignore those keypresses that the user makes while typing into some kind of text input area. How can I achieve that?
I have tried
if (document.activeElement.nodeName == 'INPUT') {
return;
}
if (document.activeElement.nodeName == 'TEXTAREA') {
return;
}
which works in those two elements; but for example, the email-compose element in Inbox by Gmail is a DIV container. Do I want to exclude all active DIVs, though? Are there other HTML elements that are used to obtain key input? Is there any much different method that I may have overlooked?

First of all, I'd use jquery to normalize your events. From there, try testing $(event.target).is():
Here is an example that has a div where all events are captured. Events for <input> elements are ignored, while others are not, including events for a <textarea>:
$('#mydiv').keypress(function(event) {
if ($(event.target).is('input')) {
return true;
} else {
console.log('not an input box');
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mydiv">
<input>
<span>Spanning area</span>
<textarea></textarea>
</div>

Related

codeBlock wrapped in <pre> inside contenteditable breaks on pressing Enter

In my custom-editor wrapping up the code in <pre> tags works fine. I would like to visually organize the pasted code for better readability. For that I need blank lines in between chunks of code. But instead of a empty line, when I press Enter, the whole code block breaks into two, with new one wrapped in its own pre-tag. The code below is supposed to be in a single-block with an empty line between example_function and another_example_function()
FYI, the contenteditable class is set to have style="display:inline-block" to prevent div.wrapper on every line. Possibly relevant CSS info - pre { white-space: pre-wrap;}. I am on chrome 83.xx. Let me know if you need any more info. Below is what I tried and failed:
//there could be several code-blocks so running a loop to get all
let preTags = document.querySelector('.custom_editor').querySelectorAll('pre')
if (preTags) {
preTags.forEach(function(item) { // attaching an event-listener to each code block
item.addEventListener('click', function(e) {
if (e.keyCode === 13) { //on enter just need a empty new line
document.execCommand('insertHTML', false, '<br>');
return false;
}
})
}
}
HTML
<div class="content" style="display:inline-block;" contenteditable="true"></div>
The nested pretags eg. contenteditable>pre do not seem like an ideal setup for events like 'keypress', 'keydown' and 'keyup' as they did respond to these events in my case. The 'click' event within pretags worked but did not process the if (e.key === 'Enter') check, so I did not follow that route.
Instead of listening to events for each pretag, I attached a listener to the container only and all of sudden my custom setting for enter-event was working inside and outside all pretags within container. Eventually I can get the empty lines within my pretags on pressing the Enter key.
document.querySelector('.custom_editor').addEventListener('keypress', someFunc)
function someFunc(e){
if (e.key === 'Enter') {
document.execCommand('insertHTML', false, "<br>");
e.preventDefault()
}
}

What causes blur?

I'm trying to make my own Wysiwyg redactor.
I have a problem: when I click the control button contenteditable div loses focus and make some actions, which I'd like to make only if was not clicked control-button.
So is there something like this in javascript:
$('#tarea').blur(function(event){
if($(event.reasonelement).is('#bold')) return false;
//Other actions here...
});
Thank you!
One way would be capturing the document's click event and decide what to do with that:
$(document).click(function(event){
elem = $("#tarea");
if (!elem.is(event.target) && elem.has(event.target).length == 0) {
// do your stuff here..
}
});
PS: This should work for all kind of elements and not just textareas.

onkeypress on a <a> tag

I'm trying get my <a> tag triggered when the user press on the "enter" key. (onkeypress).
my <a> tag:
<a href="javascript:search()" onkeypress="return runScript(event)">
this is my javascript :
function runScript(e)
{
if (e.keyCode == 13) {
alert("dssd");
return false;
}
}
I dont know whats messed up ?
its work for me
Open in new window using javascript
javaScript
window.runScript = function (e) {
if (e.keyCode == 13) {
alert('ss');
return false;
}
else {
return true;
}
}
window.search = function () {
alert('s');
}
live demo : fiddle
Write your html as given below. Note the property tabindex which makes the a tag focusable in certain browsers.
<a id="link" href="http://google.com" onkeydown="runScript(event)" tabindex="1">I am a link</a>
If you need an autofocus on load, you can use the jQuery function focus as shown below.
$(document).ready(
function(e){
$("#link").focus();
}
);
Then your function
function runScript(e){
if(e.keyCode == 13){
alert("pressed enter key");
}
}
you have to call e.preventDefault(); (or return false in some browsers) if you want to prevent the link load the link in href.
function runScript(e){
e.preventDefault();
if(e.keyCode == 13){
alert("pressed enter key");
}
return false;
}
see a demo here:
http://jsfiddle.net/diode/hfJSn/9/show press enter key when the page is loaded
The ENTER key actually triggers the onclick event:
<a href="#" onclick="alert('hello!');">
This means that your search() function inside the href will execute before the onkeypress event.
That works in my browser, though I suspect it's not the way to achieve what you actually want to do... (maybe?)
Number one, you probably don't want it to "return" anything, so you can just do onkeypress="runScript(e)" and it'll run. If that function does return a value, it's not gonna go anywhere...
Number two, it's kinda rare that a keydown event would fire on an anchor (<a>) element, unless of course the user tabs through the other elements 'till it has focus and then presses a key (usually the browser will "highlight" the element that currently has keyboard focus, if it's not just the whole page). Are you wanting your script to run when someone presses enter after typing in a search box or something? if so, you probably want to listen for the event on the search box itself, so add it as that element's onkeydown attribute (for example: <input id="mySearchBox" onkeydown="runScript(e)">) if you just want it to run whenever the user presses enter, regardless of focus or typing text into any particular field, just do as edmastermind29's comment said and add the event listener to the whole document.
Have you tried adding this to your script?
document.onkeypress = runScript;

Trigger an event when textbox contains specific keycode

I am currently working on a jQuery functionality to check a textbox for certain character values and then trigger some event depending on what character it is.
I figured the easiest way to process this would be by checking on keycodes. I have tried some different things to make the event trigger, but nothing seems to happen.
One of the things I want to check is if a textbox contains an # character (which is not allowed in the specific textbox, and it's keycode is 64 according to this site - expandinghead)
Some of the code I've attempted to use:
$("#NoEmailAllowed").live({
"keyup": function(e) {
if((e.keyCode == 64) || (e.which == 64))
{
$(this).addClass("redBg");
}
}
});
$("#NoEmailAllowed:contains('#')").live({
"keyup": function() {
$(this).addClass("redBg");
}
});
$("#NoEmailAllowed").keyup(function(){
if(this.val().contains("#"))
{
$(this).addClass("redBg");
}
});
I've tried a lot of others too, but they were quiet similar to the ones above.
So just to make everything clear about what I'm trying to achieve is:
When a user enters something in this textbox the jquery shall check for any # characters on-the-fly, and if it finds any # characters, trigger an event - for instance an alert or add a css class.
The keyup() event operates with scancodes, you're better off using keypress() to catch actual text entry (as mentioned in the jQuery documentation):
$(function(){
$('#NoEmailAllowed').keypress(function(e) {
if(e.which == 64)
{
$(this).addClass("redBg");
}
});
});
jQuery normalizes e.which, there is no need to check anything else.

Jquery : how to trigger an event when the user clear a textbox

i have a function that currently working on .keypress event when the user right something in the textbox it do some code, but i want the same event to be triggered also when the user clear the textbox .change doesn't help since it fires after the user change the focus to something else
Thanks
The keyup event will detect if the user has cleared the box as well (i.e. backspace raises the event but backspace does not raise the keypress event in IE)
$("#inputname").keyup(function() {
if (!this.value) {
alert('The box is empty');
}
});
jsFiddle
As Josh says, this gets fired for every character code that is pressed in the input. This is mostly just showing that you need to use the keyup event to trigger backspace, rather than the keypress event you are currently using.
The solution by Jonathon Bolster does not cover all cases. I adapted it to also cover modifications by cutting and pasting:
$("#inputname").on('change keyup copy paste cut', function() {
//!this.value ...
});
see http://jsfiddle.net/gonfidentschal/XxLq2/
Unfortunately it's not possible to catch the cases where the field's value is set using javascript. If you set the value yourself it's not an issue because you know when you do it... but when you're using a library such as AngularJS that updates the view when the state changes then it can be a bit more work. Or you have to use a timer to check the value.
Also see the answer for Detecting input change in jQuery? which suggests the 'input' event understood by modern browsers. So just:
$("#inputname").on('input', function() {
//!this.value ...
});
Another way that does this in a concise manner is listening for "input" event on textarea/input-type:text fields
/**
* Listens on textarea input.
* Considers: undo, cut, paste, backspc, keyboard input, etc
*/
$("#myContainer").on("input", "textarea", function() {
if (!this.value) {
}
});
You can check the value of the input field inside the on input' function() and combine it with an if/else statement and it will work very well as in the code below :
$( "#myinputid" ).on('input', function() {
if($(this).val() != "") {
//Do action here like in this example am hiding the previous table row
$(this).closest("tr").prev("tr").hide(); //hides previous row
}else{
$(this).closest("tr").prev("tr").show(); //shows previous row
}
});
Inside your .keypress or .keyup function, check to see if the value of the input is empty. For example:
$("#some-input").keyup(function(){
if($(this).val() == "") {
// input is cleared
}
});
<input type="text" id="some-input" />

Categories

Resources