KeyboardEvent object, determine if it's keyUp or down - javascript

Having a single KeyboardEvent object, is it possible to know if it corresponds to a KeyDown or KeyUp event?
(I know I can keep somewhere the event KeyUp or Down that triggers it but I am looking for a way to assess that independently of the trigger)

Look at the type property on the object you've got:
let b = document.getElementById('b');
b.onkeydown = b.onkeyup = function(e){ console.log(e.type); };
<button id="b">Button</button>

Related

Problem of using element.addEventListen("keydown", function) over document.addEventListener("keydown", function)

I have a NodeList of button elements numbers. I want each of the elements listen to keydown event in respective to their own textContent.
When I use document.addEventHandlers("keydown", function), it works fine.
Method 1:
document.addEventListener("keydown", (e)=>{
numbers.forEach(number=>{
if (number.textContent === e.key){
addNumber(number)
}})})
However, it stops working when I use this instead:
Method 2:
numbers.forEach(number=>number.addEventListener("keydown", (e)=>{
if (number.textContent === e.key){
addNumber(number);
}}))
The first method seems not efficient to me since it has to make comparison to every items in numbers everytime "keydown" is fired. Can anyone tell me why the method 2 don't work as method 1?
document.addEventListener("keydown", (e)=>{
numbers.forEach(number=>{
if (number.textContent === e.key){
addNumber(number)
}})})
In the above code, you are adding a keydown listener for the document itself, so whenever you press a key on the keyboard, this event is fired.
numbers.forEach(number=>number.addEventListener("keydown", (e)=>{
if (number.textContent === e.key){
addNumber(number);
}}))
In this code, you are adding a keydown listener to the individual element, so only if the element is focused the keydown event will be fired for that element
If the problem is the performance, you can map your numbers in a map/dictionary with their textContent as a key and the number object as a value. Then:
document.addEventListener("keydown", (e) => {
var number = numbersByKey[e.Key];
if (number)
addNumber(number);
})

Event 'e' in Javascript Function's Parameter [duplicate]

I am new to JavaScript/jQuery and I've been learning how to make functions. A lot of functions have cropped up with (e) in brackets. Let me show you what I mean:
$(this).click(function(e) {
// does something
});
It always appears that the function doesn't even use the value of (e), so why is it there so often?
e is the short var reference for event object which will be passed to event handlers.
The event object essentially has lot of interesting methods and properties that can be used in the event handlers.
In the example you have posted is a click handler which is a MouseEvent
$(<element selector>).click(function(e) {
// does something
alert(e.type); //will return you click
}
DEMO - Mouse Events DEMO uses e.which and e.type
Some useful references:
http://api.jquery.com/category/events/
http://www.quirksmode.org/js/events_properties.html
http://www.javascriptkit.com/jsref/event.shtml
http://www.quirksmode.org/dom/events/index.html
http://www.w3.org/TR/DOM-Level-3-Events/#event-types-list
DISCLAIMER: This is a very late response to this particular post but as I've been reading through various responses to this question, it struck me that most of the answers use terminology that can only be understood by experienced coders. This answer is an attempt to address the original question with a novice audience in mind.
Intro
The little '(e)' thing is actually part of broader scope of something in Javascript called an event handling function. Every event handling function receives an event object. For the purpose of this discussion, think of an object as a "thing" that holds a bunch of properties (variables) and methods (functions), much like objects in other languages. The handle, the 'e' inside the little (e) thing, is like a variable that allows you to interact with the object (and I use the term variable VERY loosely).
Consider the following jQuery examples:
$("#someLink").on("click", function(e){ // My preferred method
e.preventDefault();
});
$("#someLink").click(function(e){ // Some use this method too
e.preventDefault();
});
Explanation
"#someLink" is your element selector (which HTML tag will trigger this).
"click" is an event (when the selected element is clicked).
"function(e)" is the event handling function (on event, object is created).
"e" is the object handler (object is made accessible).
"preventDefault()" is a method (function) provided by the object.
What's happening?
When a user clicks on the element with the id "#someLink" (probably an anchor tag), call an anonymous function, "function(e)", and assign the resulting object to a handler, "e". Now take that handler and call one of its methods, "e.preventDefault()", which should prevent the browser from performing the default action for that element.
Note: The handle can pretty much be named anything you want (i.e. 'function(billybob)'). The 'e' stands for 'event', which seems to be pretty standard for this type of function.
Although 'e.preventDefault()' is probably the most common use of the event handler, the object itself contains many properties and methods that can be accessed via the event handler.
Some really good information on this topic can be found at jQuery's learning site, http://learn.jquery.com. Pay special attention to the Using jQuery Core and Events sections.
e doesn't have any special meaning. It's just a convention to use e as function parameter name when the parameter is event.
It can be
$(this).click(function(loremipsumdolorsitamet) {
// does something
}
as well.
In that example, e is just a parameter for that function, but it's the event object that gets passed in through it.
The e argument is short for the event object. For example, you might want to create code for anchors that cancels the default action. To do this you would write something like:
$('a').click(function(e) {
e.preventDefault();
}
This means when an <a> tag is clicked, prevent the default action of the click event.
While you may see it often, it's not something you have to use within the function even though you have specified it as an argument.
In jQuery e short for event, the current event object. It's usually passed as a parameter for the event function to be fired.
Demo: jQuery Events
In the demo I used e
$("img").on("click dblclick mouseover mouseout",function(e){
$("h1").html("Event: " + e.type);
});
I may as well have used event
$("img").on("click dblclick mouseover mouseout",function(event){
$("h1").html("Event: " + event.type);
});
Same thing!
Programmers are lazy we use a lot of shorthand, partly it decreases our work, partly is helps with readability. Understanding that will help you understand the mentality of writing code.
Today I just wrote a post about "Why do we use the letters like “e” in e.preventDefault()?" and I think my answer will make some sense...
At first,let us see the syntax of addEventListener
Normally it will be:
target.addEventListener(type, listener[, useCapture]);
And the definition of the parameters of addEventlistener are:
type :A string representing the event type to listen out for.
listener :The object which receives a notification (an object that implements the Event interface) when an event of the specified type
occurs. This must be an object implementing the EventListener
interface, or a JavaScript function.
(From MDN)
But I think there is one thing should be remarked:
When you use Javascript function as the listener, the object that implements the Event interface(object event) will be automatically assigned to the "first parameter" of the function.So,if you use function(e) ,the object will be assigned to "e" because "e" is the only parameter of the function(definitly the first one !),then you can use e.preventDefault to prevent something....
let us try the example as below:
<p>Please click on the checkbox control.</p>
<form>
<label for="id-checkbox">Checkbox</label>
<input type="checkbox" id="id-checkbox"/>
</div>
</form>
<script>
document.querySelector("#id-checkbox").addEventListener("click", function(e,v){
//var e=3;
var v=5;
var t=e+v;
console.log(t);
e.preventDefault();
}, false);
</script>
the result will be : [object MouseEvent]5 and you will prevent the click event.
but if you remove the comment sign like :
<script>
document.querySelector("#id-checkbox").addEventListener("click", function(e,v){
var e=3;
var v=5;
var t=e+v;
console.log(t);
e.preventDefault();
}, false);
</script>
you will get : 8 and an error:"Uncaught TypeError: e.preventDefault is not a function
at HTMLInputElement. (VM409:69)".
Certainly,the click event will not be prevented this time.Because the "e" was defined again in the function.
However,if you change the code to:
<script>
document.querySelector("#id-checkbox").addEventListener("click", function(e,v){
var e=3;
var v=5;
var t=e+v;
console.log(t);
event.preventDefault();
}, false);
</script>
every thing will work propertly again...you will get 8 and the click event be prevented...
Therefore, "e" is just a parameter of your function and you need an "e" in you function() to receive the "event object" then perform e.preventDefault(). This is also the reason why you can change the "e" to any words that is not reserved by js.
It's a reference to the current event object
this will be my first stackoverflow help but I am confident that my answer will help anyone reading this.
Basically, e is just an object containing information about the EVENT which has just occured.
if it is 'click', then the object will contain about the click,
if it is 'submit', then the object will contain about the submit,
and they are typically found in addEventListener.
clickMe.addEventListener('click', e => {
console.log(e)
}
meaning, whenever I 'click' the button, it will console.log the INFOMRATION about the event that happened which is I did is to 'click' it, this will print information about the click event.
e is very useful because you can access and use the event to your very own project such as printing the location of x value... like
clickMe.addEventListener('click', e => {
console.log(e.clientX)
}
then it will print the location where you 'click' that event.. mine it returns 32
if you prefer video, please watch this
https://www.youtube.com/watch?v=_BVkOvpyRI0
video is not mine
upvoting me will truly help me since I am a student and looking for opportunity to help here. Love lots!
$(this).click(function(e) {
// does something
});
In reference to the above code
$(this) is the element which as some variable.
click is the event that needs to be performed.
the parameter e is automatically passed from js to your function which holds the value of $(this) value and can be used further in your code to do some operation.

How to pass event as argument to an inline event handler in JavaScript?

// this e works
document.getElementById("p").oncontextmenu = function(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
};
// this e is undefined
function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
<p id="p" onclick="doSomething(e)">
foo
<span>bar</span>
</p>
There are some similar questions have been asked.
But in my code, I'm trying to get child elements who's been clicked, like a or span.
So what is the correct way to pass event as an argument to event handler, or how to get event inside handler without passing an argument?
edit
I'm aware of addEventListener and jQuery, please provide a solution for passing event to inline event hander.
to pass the event object:
<p id="p" onclick="doSomething(event)">
to get the clicked child element (should be used with event parameter:
function doSomething(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
to pass the element itself (DOMElement):
<p id="p" onclick="doThing(this)">
see live example on jsFiddle.
You can specify the name of the event as above, but alternatively your handler can access the event parameter as described here: "When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters". There's much more additional documentation at the link.
You don't need to pass this, there already is the event object passed by default automatically, which contains event.target which has the object it's coming from. You can lighten your syntax:
This:
<p onclick="doSomething()">
Will work with this:
function doSomething(){
console.log(event);
console.log(event.target);
}
You don't need to instantiate the event object, it's already there. Try it out. And event.target will contain the entire object calling it, which you were referencing as "this" before.
Now if you dynamically trigger doSomething() from somewhere in your code, you will notice that event is undefined. This is because it wasn't triggered from an event of clicking. So if you still want to artificially trigger the event, simply use dispatchEvent:
document.getElementById('element').dispatchEvent(new CustomEvent("click", {'bubbles': true}));
Then doSomething() will see event and event.target as per usual!
No need to pass this everywhere, and you can keep your function signatures free from wiring information and simplify things.
Update 2022-10-30:
I have contacted someone from WHATWG, and another way it could be done is below, although some IDE's report it as "obsolete" which it's not. You could pass the "event" keyword in your caller's argument list, in any position, and use it as such. It would be event with a small e.
Below would work, a, b, c and d being extra arguments to pass if any, to demonstrate the order doesn't matter:
<p onclick="doSomething(a,b,event,c,d)">
And in your function definition, you would capture it accordingly:
function doSomething(arg1, arg2, arg3, arg4, arg5){} //arg3 would contain the event
And access the usual properties, in this case since we wired event with arg3:
console.log(arg3.target)
Since inline events are executed as functions you can simply use arguments.
<p id="p" onclick="doSomething.apply(this, arguments)">
and
function doSomething(e) {
if (!e) e = window.event;
// 'e' is the event.
// 'this' is the P element
}
The 'event' that is mentioned in the accepted answer is actually the name of the argument passed to the function. It has nothing to do with the global event.
Here is how I would do it to prevent users from copying and pasting invalid characters into input text fields:
function validatePaste(el, e) {
var regex = /^[a-z .'-]+$/gi;
var key = e.clipboardData.getData('text')
if (!regex.test(key)) {
e.preventDefault();
return false;
}
}
This function is located inside <script> tags and it is called like:
<input type="text" onpaste="validatePaste(event)">

Reset element to "default" event

In Javascript, how can you set the event handler of a DOM element to default behavior?
For example, suppose I set the onkeypress event of an input element:
elem.onkeypress = function() { alert("Key pressed!"); }
Later, how can I remove this event? Is it okay to simply set the onkeypress property to null? I tried that and it works, but I don't know if it is the proper way to do this.
I'm pretty sure that the events will be undefined rather than null, so you'd be better off setting back to that.
It's probably overkill, but to be more robust, you're arguably better off keeping a reference to whatever used to be registered to the onkeypress event & reassign that (just in case some other script is trying to use it too). So:
var oldKeyPress = elem.onkeypress;
elem.onkeypress = function() { alert("Key pressed!"); }
//... later ...
elem.onkeypress = oldKeyPress;

why my code that write by me is upper,when keyup

$('#a').keyup(
function(event){
alert(event.keyValue)
}
)
but error,coz 'keyValue' is not undefined,
how do i get the keyValue when the event keyup???
i use jquery.
thanks
i do this:
$('#a').keyup(
function(event){
alert(String.fromCharCode(event.which))
}
but it alert the value of upper
ex:
i alert I
l alert L
why???
)
try event.keyCode instead
JQuery places the key pressed into event.which across all browsers.
See here: http://api.jquery.com/keyup/
To determine which key was pressed, we
can examine the event object that is
passed to the handler function. While
browsers use differing attributes to
store this information, jQuery
normalizes the .which attribute so we
can reliably use it to retrieve the
key code
Check out this question: jQuery Event Keypress: Which key was pressed?

Categories