target "this" on addEventListener event [duplicate] - javascript

This question already has answers here:
addEventListener, arrow functions, and `this` [duplicate]
(1 answer)
What does "this" refer to in arrow functions in ES6?
(10 answers)
Closed last year.
So I'm dealing with a little problem..
I'm trying to modify drag-and-drop code and came across a problem, since I want to have multiple drop areas and one function for all of them.
I have this code:
dropArea.addEventListener("dragover", (event)=>{
event.preventDefault(); //preventing from default behaviour
dropArea.classList.add("activated");
dragText.textContent = "🖐 Release to Upload File";
});
And specified dropareawitth querySelector:
const dropArea = document.querySelector(".drag-area")
Now I need to modify it to work with multiple drop zones. I thought to just replace the "droparea" inside the event to "this" something like that:
this.classList.add("activated");
but it does not work. I even tried:
$(this).classList.add("activated");
Returns this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'add')
Any solutions? I'm stuck...

As your event handler is an arrow function, the value of this is not influenced by the caller, so you cannot use it to get the DOM element. You can use event.target.
event.target.classList.add("activated");
As to your final attempt: $() does not return a DOM element, but an array-like "jQuery" collection object, which doesn't have such properties as classList.

Related

Undefined after using addEventListener [duplicate]

This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
Closed 1 year ago.
I am very new to Javascript and am trying to translate a game i made in python into javascript. I am currently trying to get keyboard input for the game. Whenever i run this however it gives me the following error:
Uncaught TypeError: Cannot read property '0' of undefined(at line 4 in this example)
Board is a 2d array used to store the board and i have tested that before the addEventListener statement Board is not undefined.
Why is this error happening and what should i do to fix it. As mentioned before i am a complete beginner at javascript so simple explanations would be greatly appreciated.
Kind regards
document.addEventListener('keydown', function(event){
if(event.keyCode == 65){
console.log(Board)
Board[this.block1[0]][this.block1[1]]=null;
Board[this.block2[0]][this.block2[1]]=null;
Board[this.block3[0]][this.block3[1]]=null;
Board[this.block4[0]][this.block4[1]]=null;
this in your code is not what you expect it to be. If block1 etc are local variables, reference them without this.. If they are members of your encapsulating object, change your callback function to use arrow syntax to let this reference your object: document.addEventListener('keydown', event => { /*...*/ })

Can we skip the parameter in event function? [duplicate]

This question already has answers here:
Why Firefox says that window.event is undefined? (call function with added event listener)
(6 answers)
Closed 1 year ago.
Cuz if I skip it, the output is the same. Why we need it?
<p id='p'>TEXT</p>
<script>
p.onclick=function(event){ //with parameter
alert(event.target.tagName); //P
}
</script>
Now skip event, same output.
<p id='p'>TEXT</p>
<script>
p.onclick=function(){ //without parameter
alert(event.target.tagName); //P
}
</script>
Many tutorial will keep the parameter, I wonder why we need it? Why don't we make it simple? I just keep the original name of event in the function and it works out.
Because window.event is deprecated and is not supported by all browsers.
You should avoid using this property in new code, and should instead use the Event passed into the event handler function. This property is not universally supported and even when supported introduces potential fragility to your code.

JS: Why is the Event object accessible in event handlers without accepting it in a parameter? [duplicate]

This question already has an answer here:
Javascript events: window.event vs argument reference (function)
(1 answer)
Closed 5 years ago.
While looking back over some JS I'd written in the past, I noticed that I was trying to access event.keyCode in an event handler, but my function's only parameter was e, not event. So, while I would expect to get a "Uncaught ReferenceError: event is not defined", I instead found that my script works as expected (at least in Chrome).
document.body.addEventListener('keyup', function(e) {
if (event.keyCode === 13) {
// ...
}
});
In fact, if I place a console.log(e === event) in that handler, I get true.
After a little testing (in a JS Bin) it seems like this must apply to every such event, making event another sort of "sly" local variable like arguments that appears in a function without asking for it in a parameter.
This makes me wonder:
Are these the only two "sly" local variables?
Is this behavior with event in Chrome consistent with other browsers & JS environments?
Depending on the browser, there is a global event variable that refers to the currently fired event.

jQuery "this" inside click [duplicate]

This question already has answers here:
var self = this?
(8 answers)
Closed 7 years ago.
So I have something like
this.editElement = $("<a href='#'>Edit</a>").click(function() {
this.startEdit();
});
This however takes "this" to be the editElement itself, rather than the parent object.
I've managed to get it to work by making a
var parent = this;
before setting click and then using parent enough of this.
Is this the correct way to solve the problem?
That's a very correct way, yes, and it's common.
You also took the right decision in naming it parent instead of the semantic-less _this we often see.
Other solutions :
to bind the callback to the external this
to use the data argument of JQuery's on to pass the parent
to dynamically find the parent from the callback
but most often referring to a variable kept in the external closure as you did is the cleanest solution.

how to rebind the onclick property in javascript [duplicate]

This question already has answers here:
jQuery equivalent of JavaScript's addEventListener method
(7 answers)
Closed 8 years ago.
I have the below code where I successfully disable the properties
.prop("onclick", null)
.prop("onmouseover", null)
.prop("onmouseout", null);
Now if I want to rebind the click event what should I do.
For adding events back to a element use the bind function.
$("YourElement").bind("event",function(){
//Do what you want.
}
You can do it with many ways. I don't use to call the prop() method, but I think you just have to use it and set as your second parameter the name of your function.
function yourFunction()
{
// The job with onclick
}
DOMElement.prop("onclick", "yourFunction");
You can also use anonymous functions.
Use this documentation to work : http://api.jquery.com/prop/
I suggest you should use removeProp() instead of prop("yourprop", null) !

Categories