Javascript get event from this - javascript

I am trying to move from inline onkeyup event and changed my input from
<input name="some1" id="some1" onkeyup="ajax_autocomplete('some1',this.value,event);">
to
<input name="some1" id="some1" class="autoc">
and after page load
var acinputs = document.querySelectorAll('.autoc');
for(var i=0; field=acinputs[i]; i++)
{
field.onkeyup = function() {update.call(this);}
function update()
{
var text = this.value;
// How to get keycode now from event?
// Before: var kc=event.which;if(kc==undefined){kc=event.keyCode}
}
}
My problem is that while I was getting event data inline like keycode from the event before but I do not know how to get it from event now? this.value gives me the text entered in the input however this.event does not work! I know this.event is not the proper way of getting event from this !
I am not using jQuery.

Add event as parameter
In my example event is referred to ev.
field.onkeyup = function(ev) {update.call(this, ev);}
function update(th, ev)
{
var text = th.value;
var kc=ev.which;
if(kc==undefined) {
kc=ev.keyCode
}
}

Related

How to trigger an html button and its onclick function with a hardware keyboard key?

I'm a newbie to coding, and this topic is probably very common, but it has me pretty confused.
I have a button:
<button onclick = typeWriter()>/click</button>`
My function:
var myArray = ['such', 'something else', ];
var rand = myArray[Math.floor(Math.random() * myArray.length)];
var i = 0;
var speed = 55;
function typeWriter() {
if (i < rand.length) {
document.getElementById("question").innerHTML += rand.charAt(i);
i++;
setTimeout(typeWriter, speed);
}
}
How do I add a keyboard key like the spacebar as an event listener or something similar, so that when I press the spacebar (and not in a text box), it presses the button and triggers the function? A simple vanilla javascript answer would be preferable, since I don't get jQuery.
Would it be better to simply add script that triggers myFunction with the spacebar rather than going through triggering the button? And if so, how do I program that?
BTW: I'm trying to do this for mobile, using an iPad keyboard. Will that change anything?
Thanks.
You can add a listener on window if you want to trigger your function everywhere of your html.
window.onkeydown = function(event) {
if (event.keyCode == 32) {
//your function here
};
};
Here you can find all key codes for keyboard: https://keycode.info/
don't use inline JS
Use addEventListener()
Use Event.key to determine the pressed key
Use a helper function to determine if the current Event.target is a FormElement
// Function to detect if el is a form element
const isFormElement = el => /^(input|textarea|select|button)$/i.test(el.nodeName);
// Example function
const myFunction = ev => console.log("HELLO!");
// Find buttons in DOM
const EL_myfn = document.querySelectorAll('.js-myFunction');
// Trigger directly on buttons click
EL_myfn.forEach(el=> el.addEventListener('click', myFunction));
// And on keydown
window.addEventListener('keydown', ev => {
// If spacebar is hit, and we're not inside a forminput element
if (ev.key === " " && !isFormElement(ev.target)) {
myFunction();
}
})
textarea{width: 100%;}
<button class="js-myFunction">Click me! (Console should log)</button>
<div>press spacebar here (Console should log)</div>
<textarea>press spacebar here (Console should not log!!)</textarea>

Reactjs keypress regex?

Using ReactJS, I am trying to set a keypress regex listener. My code is below.
formation: function() {
var f1c = document.getElementsByClassName('f1t').value;
var validator = new RegExp('^[0-9.]*$');
var runner = validator.test(f1c);
var bling = document.getElementById('f1p2');
if (runner) {
alert("Vegetables");
} else {
alert("Fruits");
}
},
This is called from a separate function, like so.
something: function() {
return (
<input type="text" className="f1t" onKeyUp={this.formation}>something</p>
);
}
The problem is that the keyup event only runs as it should if I remove the if arguments, meaning that the keyup does work. However, there must be something off with my logic.
The code as shown above keeps showing Fruits when it is only supposed to show fruit if the value of f1c is not a number.
It's not good to directly access the DOM in React. Take a look at the following link to see best practices for handling form updates:
https://facebook.github.io/react/docs/forms.html
<input type="text" onKeyUp={this.formation}>something</p>
formation: function(event) {
var f1c = event.target.value;
...
}
When a user presses a key, and the event fires, the function will get a reference to the element and the key in the form of a React synthetic event.
formation: function(e) {
var theKeyPressed = e.charCode; // this is normalized for you by React
var theElementPressed = e.target;
var theValueOfTheElement = e.target.value;
// do your thing
},
something: function() {
return (
<input type="text" className="f1t" onKeyUp={this.formation}>something</p>
);
}
FYI, type="text" is redundant nowadays, it's the default.

Javascript: Best event to use to call function for any change in text area?

I want a function to be called whenever there is any change within my text area, i.e. char typed, removed, cut, pasted etc.
Currently I am using:
onkeyup || onmousemove = function();
This seems to only be calling onmousemove, what can I use to call my function on ANY change to the textarea.
I am creating this JS as a string to add it as a parameter to the creation of a text_area using codeigniteras described here at form_input section
e.g:
$js= 'onkeyup || onmousemove = "function()"';
echo text_area('name', " ", $js);
There's no way to combine multiple HTML attribute assignment, you have to do them separately. Try:
text_input('name', ' ', 'onkeyup="function()" onmousemove="function()"');
try this :
$('#element').on('keyup keypress blur change', function() {
...
});
Just give textarea an id say myId and bind events to it to trigger handler.
var element = document.getElementById("myId");
var myEvents = "oninput onchange onkeyup onpaste".split(" ");
var handler = function (e) {
};
for (var i=0, len = myEvents.length; i < len; i++) {
element.addEventListener(myEvents[i], handler, false);
}
Try something like below
Example
<textarea id='textarea1'>data</textarea>
//....................
$("textarea").bind('input propertychange', function(){
alert($(this).val());
});
Note: Use jquery plugin
DEMO
If you want to prevent simultaneous triggers then use the below code
<textarea id="textarea"></textarea>
//.......
var text = "";
$("#textarea").on("change keyup paste", function() {
var Val = $(this).val();
if(Val == text) {
return; //prevent multiple simultaneous triggers
}
text = Val;
alert("changed!");
});
DEMO2

Javascript events in Firefox for javascript assigned listeners

OK, so there's a question that gets asked around here a lot about Firefox not responding to window.event, where instead you need to add an extra parameter to the function. I have no problems with that; my problem is how the heck do I do that if I want to assign the event listeners from within a different Javascript function?
Basically, what I'm trying to do is the common effect when you can have a form box that has grey text that would say, for example, "Your name..." and then when you click the box the text disappears and the color changes to black; unfocus with the box still empty and the prompt text will return.
Now, instead of coding this directly for every page I want to use it on, I'm trying to make a function that I can call with the ID of the form and it will automatically apply this to every input element. Here's the code:
function fadingForm(formElementID, endColor)
{
var form = document.getElementById(formElementID);
for(var i = 0; i < form.elements.length; i++)
{
form.elements[i].originalValue = form.elements[i].value;
form.elements[i].originalColor = form.elements[i].style.color;
form.elements[i].changedColor = endColor;
// Somehow I need to get that event parameter in here I guess?
// I tried just putting the variable event in as a parameter,
// but as you'd expect, that doesn't work.
form.elements[i].onfocus = function() { focused(); };
form.elements[i].onblur = function() { blurred(); };
}
}
function focused(e)
{
evt = e || window.event;
element = evt.target;
if(element.value == "" || element.value == element.originalValue)
{
element.value = "";
element.style.color = element.changedColor;
}
}
function blurred(e)
{
evt = e || window.event;
element = evt.target;
if(element.value == "" || element.value == element.originalValue)
{
element.value = element.originalValue;
element.style.color = element.originalColor;
}
}
And of course, this works perfectly in Chrome, Safari, etc...just not Firefox.
Your event listeners focused and blurred accept an event object e, but you never provide an event object. The event object that is provided to the anonymous wrapper functions is never used nor passed to focused/blurred. Thus, e is always undefined.
Instead, when you set up your listeners, do:
form.elements[i].onfocus = function(e) { focused(e); };
form.elements[i].onblur = function(e) { blurred(e); };
Or even:
form.elements[i].onfocus = focused;
form.elements[i].onblur = blurred;
So that the event object is passed directly into your listener functions.

Invoke a function after right click paste in jQuery

I know we can use bind paste event as below:
$('#id').bind('paste', function(e) {
alert('pasting!')
});
But the problem is, that it will call before the pasted text paste. I want a function to be triggered after the right click -> paste text pasted on the input field, so that I can access the pasted value inside the event handler function.
.change() event also doesn't help. Currently I use .keyup() event, because I need to show the remaining characters count while typing in that input field.
Kind of a hack, but:
$("#id").bind('paste', function(e) {
var ctl = $(this);
setTimeout(function() {
//Do whatever you want to $(ctl) here....
}, 100);
});
Why not use the "input" event?
$("#id").bind('input', function(e) {
var $this = $(this);
console.log($this.val());
});
This will stop user from any pasting, coping or cutting with the keyboard:
$("#myField").keydown(function(event) {
var forbiddenKeys = new Array('c', 'x', 'v');
var keyCode = (event.keyCode) ? event.keyCode : event.which;
var isCtrl;
isCtrl = event.ctrlKey
if (isCtrl) {
for (i = 0; i < forbiddenKeys.length; i++) {
if (forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
return false;
}
}
}
return true;
});
This one will do the same for the mouse events:
$("#myField").bind("cut copy paste",function(event) {
event.preventDefault();
});
Even though the above one will not prevent right clicks, the user will not be able to paste, cut or copy from that field.
To use it after the event, like you wondered on your question, you must use JavaScript Timing Event
setTimeout(function() {
// your code goes here
}, 10);
I had the same issue, I opted to replicate the paste action through javascript and use that output instead:
var getPostPasteText = function (element, pastedData) {
// get the highlighted text (if any) from the element
var selection = getSelection(element);
var selectionStart = selection.start;
var selectionEnd = selection.end;
// figure out what text is to the left and right of the highlighted text (if any)
var oldText = $(element).val();
var leftPiece = oldText.substr(0, selectionStart);
var rightPiece = oldText.substr(selectionEnd, oldText.length);
// compute what the new value of the element will be after the paste
// note behavior of paste is to REPLACE any highlighted text
return leftPiece + pastedData + rightPiece;
};
See IE's document.selection.createRange doesn't include leading or trailing blank lines for source of the getSelection function.
No need to bind :
$(document).on('keyup input', '#myID', function () {
//Do something
});

Categories

Resources