JavaScript eventListener mousemove - javascript

How does the u log in the value of the coordinate of the mouse?
div = document.querySelector('.div');
div.addEventListener('mousemove', function yo(u) {
console.log(u);
});
This logs the value of x and y coordinate of the mouse.

According to this API reference:
document.addEventListener(event, function, useCapture)
is the function prototype that takes in an event type string as the first argument a "callback" function as the second argument and a third argument true or false indicating in which phase the function should be called.
When the callback activates an event object is passed to the declared function, the type depending on the type of callback.
In the case of "mousemove" the argument passed into the function by the web browser contains all sorts of useful information
According to this Mozilla developer reference, in newer versions of firefox and chrome the console.log function only stores a reference to the object passed into the web browser "which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you click it open."
All of the non global values will be relative to .div
Hope this helps.

From the MDN:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
target.addEventListener(type, listener[, options]);
listener is 'an object implementing the EventListener interface, or a JavaScript function.' (emphasis mine)
You're just passing in a named function (in this case named 'yo'). It would work just as well as an anonymous function. That is:
div.addEventListener('mousemove', function(x) {
console.log(x);
});

Related

I need some explanation about some syntax

I have seen this kind of code in one of Google's google maps documentation. My question is about the listener. Instead of the callback function passed immediately after the 'click' action the showArrays() function is called but not passed nothing as parameter. On the other hand showArrays() function uses event as parameter. Please explain me this kind of calling the function.
element.addListener('click', showArrays);
//some code here
}
function showArrays(event) {
// some code here
}
Think of the names of functions as variables themselves. showArrays is a variable, that, when given an event, does something with it.
You can pass the functions name as a parameter to addListener so that it can call the callback when the element is clicked on. It's important to note that you are not calling the function in the first line, only passing a reference to that function.
You can show this property in the browser's console with this test:
function test() { console.log("Test was called"); }
Notice if you say var x = test nothing is printed to the console. But if you say var x = test() you see the print. Finally, if you do var x = test; x() you will see the print out, because you called the test function after assigning it a new name.
Notice that in the element.addListener('click', showArrays) line, showArrays does NOT have brackets after it. That means it's not being called. Instead, the entire function is being passed as a parameter to the addListener method.
Event listeners in JS will take the handler function you provide when you attach them with addListener (or addEventListener, more commonly), and, when the event occurs, they will call that function and pass an event object to it.
In other words, showArrays is not being called until the element is clicked, and all event listeners inherently get passed an event object at that point, detailing the specific properties of the event.
One of the syntax cases for describing a function is:
var showArrays = function (event) {
// of the code here
}
and it is precisely this argument value that the addEventListener method uses, and even other functions such as setTimeout or setInterval, among others.
addEventListener method always sends the "event" object as an argument to the callback function. When you use the anonymous function, it is obvious to see it:
element.addEventListener('click', function(event) {
// some code here
});
But when you send to the addEventListener method a link to the function you want to be called when the event occures (in your case it is a link to showArrays function), addEventListener sends "event" object as an argument to this function just on itself. So, although it's not obvious to see it, but the "event" object is being sent to showArrays function automatically.
element.addEventListener('click', showArrays); // the event object will be sent automatically
And you will have an access to the "event" object inside the showArrays function. But, of corse, in showArrays function declaration you should have a parameter for catching the "event" object.
function showArrays() {} // it's not going to work
function showArrays(event) {} // it will work

Why does javascript handleEvent method have access to event with event parameter omitted?

According to MDN doc handleEvent method has event as its single parameter, however it this example:
Codepen
html code:
<button id="btn">Click here!</button>
javascript code:
const buttonElement = document.getElementById('btn');
buttonElement.addEventListener('click', function () {
alert(event.type);
});
The callback handleEvent function has no parameters yet can access event (it alerts 'click').
How does it work?
Is there any reference explicitly state that event parameter can be omitted?
In JavaScript, when you reference a variable, it will first look in the local scope before checking the global scope. In your browser, all globally scoped variables are properties of the window object. Looking up window.event yields the following article: https://developer.mozilla.org/en-US/docs/Web/API/Window/event. Notably:
The read-only Window property event returns the Event which is currently being handled by the site's code. Outside the context of an event handler, the value is always undefined.
This means that any time you are currently handling an event, the browser also binds that event to the global scope.
It should be noted that, as mentioned in the article, actually taking advantage of this is a bad idea. The value is not always what you would expect, and using global variables in general is not preferred.
As for your second question: Any parameter of any callback function can be omitted as long as you don't plan to use it in your handling, and if you do include it you can name it what you like. In this case, it just so happens that there is a global variable that has the same name as the name commonly used for that parameter. The exception to this is that you do have to define all previous parameters to access later ones.
Some examples:
// This is OK - you don't have to call the passed event "event"
buttonElement.addEventListener('click', function (ev) {
alert(ev.type);
});
// This is not OK - the global variable is named "event" so "ev" in this case is undefined
buttonElement.addEventListener('click', function () {
alert(ev.type);
});
// This is OK but not preferred because it uses the global "event" variable
buttonElement.addEventListener('click', function () {
alert(event.type);
});
// This the same as the preceding example
buttonElement.addEventListener('click', function () {
alert(window.event.type);
});

Pass function reference as event handler in jQuery

I am trying to pass function reference as event handler in jQuery. I would like to use a shorthand like in the simple example below...
$("a").click(console.debug.bind(undefined,this));
...rather than passing explicitly the whole function body:
$("a").click(function() {
console.debug(this)
});
Moreover, I would like to access elements selected by jQuery in my shorthand function (and pass them as a parameter). In other words: I expect to have a result of $("a") as a this (or any other code that will retrieve the result).
So far I've tried:
var a = function() {
console.debug(this);
};
var b = console.debug.bind(undefined,this);
$("a").click(function() {console.debug(this)}); // prints link
$("a").click(a); // prints link
b(); // prints Window
$("a").click(console.debug.bind(undefined,this)); // prints Window & jQuery.Event
Here is the fiddle:
https://jsfiddle.net/hbqw2z93/1/
My questions are:
Is it possible to use such construction and meet all requirements, without definition of additional variables - just one line as shown above?
Is it possible to access jQuery's selection result using described approach?
Why in the given scope this becomes 'merged' Window and jQuery.Event object?
You already using it, aren't you? :) It's limited, but it works in your own fiddle
jQuery will pass event object to your specified function. You can use function bind to pass that as an argument (you already have this working in your fiddle)
It doesn't. See what's happening:
jQuery passed one argument to click handler function - event object. You pass console.debug.bind(undefined, this) as a handler function so jQuery will call it with one argument.
Then, when you are binding you are asking to use 'undefined' as a 'this' object inside the function and sending an extra argument - 'this', which is a Window at this scope because you are binding at the highest level.
So when actual click happens, jQuery calls console.debug with two parameters - Window object that was bound during click() and jQuery event that is always passed to click handler. console.debug() can accept and display multiple objects, which is exactly what you see in the developer console.
The first parameter of bind is the new context to use for this. By passing undefined you are essentially not passing the first parameter.
The second and further parameters are passed into the function as the first values.
Note also that this when in the global scope, refers to the window object.
So here, b...
console.debug.bind(undefined,this);
is identical to...
function(){ console.debug(window); }
..since you're passing this (which is window) as the first parameter to debug.
By default, when you attach an event to the element, this will automatically point to the element which caught the event, so bind shouldn't even be necessary, which is why $("a").click(a); worked without using bind.

What is the meaning of 'function(event)' in js

I don't know the meaning of the sentence 'function(event)'
Event.add(apple,'click',function(event) {
Event.stopPropagation(event);
});
Isn't the argument 'event' is the unique keyword of javascript?
Is keyword can be an argument of some function?
I understand the meaning of below code :
function(test) {
alert(test);
}
But I don't understand this one :
function(event)...
Can any one give an explanation about that to me?
The event object is always passed to the handler and contains a lot of useful information what has happened.
Different types of events provide different properties. For example, the onclick event object contains:
event.target - the reference to clicked element. IE uses event.srcElement instead.
event.clientX / event.clientY - coordinates of the pointer at the moment of click.
Information about which button was clicked and other properties.
Please visit this link.
It answers all your questions very simply
Source http://javascript.info/tutorial/obtaining-event-object
Example:
Like if in HTML you have assigned an event like this
<button onclick="alert(event)">See the event</button>
then
function alert(event) {
// event.type contains whether this event was invoked in the result of a click etc
// event.target would contain the reference to the element which invoked this method/event
}
It is an anonymous function, that is a function without name, that sends the event object. That object contains information about the event itself. It is always passed as first object/variable.
It is defining an anonymous function object. This code:
function foo(bar) { ... }
Is functionally similar to:
var foo = function (bar) { ... };
(Except that in the first case the name foo and the creation and assignment of the function object are hoisted to the top of the scope, while in the second case only the name foo is hoisted; foo won't hold the function until the assignment executes.)
Effectively, the code you posted is calling Event.add() and passing a function to it as the third argument, but rather than declaring the function ahead of time it is creating the function object inline.
Another way to write the code block in your question is:
function handler(event) {
Event.stopPropagation(event);
}
Event.add(apple, 'click', handler);
Except that the code in your question does not introduce the handler name.
Note that there is no such method Event.stopPropagation(). However, the event object will have a stopPropagation(), so the capital E was probably a typo. It's likely that the intent was to use function (event) { event.stopPropagation(); }.
event is just a variable that's passed to event listener functions such as Event.add, element.on. It's not reserved (although Event is, which is why you can use Event.add), and you can name it whatever you like.
The event argument is used to pass information about the event that has happened (the click on apple in this case), which can be used to retrieve data about the event or manipulate it.
function(){...} is an anonymous function, which means that you don't need to name it, you can just declare it inline, and the function will be passed as an argument, as if you said
function foo (event) {
...
}
Event.add(apple, "click", foo);
but you don't need to declare it before hand. It does come at the disadvantage of not being duplicable, for instance when clearing an event handler.
Look at the event variable and you will all understand :)
function (event) {
console.log({ event });
}

How does the event parameter work in javascript?

function(e){
if(e.which==='37'){
//
}
}
After I search for how does this e or event parameter work on the internet for while, I still did not find an answer..
Assume e has not been defined before this function call... what will e become after this function call? an Object?
Does the which cause it to become a object?
can we pass a undefined variable into a function in javascript? what are expected to happen if I did so?
The variable e is a parameter of the function. Forget about events for a minute and consider this function:
function doStuff(e) {
alert(e.which);
}
This function accepts something called e and alerts the which property of that value. Note that this function is the same as:
function doStuff(firstParam) {
alert(firstParam.which);
}
This shows that we can call the parameter anything we like, but we've chosen to call it e.
You could invoke the function directly like:
doStuff({ which: 46 });
doStuff({ which: 57 });
doStuff({ which: "Bob" });
Each of these invokes doStuff and passes in some object with a which property, which the doStuff function body refers to as e.
Now suppose we use doStuff as an event listener:
document.addEventListener("keypress", doStuff);
This tells the browser to invoke doStuff every time the user presses a key. What gets used as the e value depends on which key caused the keypress event to occur.
what will e become after this function call?
e does not exist outside of this function. JavaScript scope is function-based, and e is limited in scope to this function, since it is a formal parameter of the function.
Does the which cause it to become a object?
No, the which is simply an object property of the Event object that is supplied as the e parameter. When a function is invoked as an event listener, the value passed as the function 's first parameter is always an object (specifically, an Event object, with details about the event).
Assume e has not been defined before this function call... what will e become after this function call?
Nothing. It will remain undefined.
Normally, you would use a function like this as an event handler. In that case, the event object (the use of which implies a keyboard event if you want to be specific) is created by the code that calls the function.
For the most part, that code will be built into the browser and not written by you directly.

Categories