I'm new to JavaScript and I wonder why it's not working for me:
function resetColor(){
$(this).css( { "color": "red" } )
}
$('.class').click(function() {
resetColor();
});
I also tried to save $(this)
as a variable when clicking the .class
, but that didn't work for me also.
When you declare the variable inside function . It has its scope limited to that function only(In case one of your scenario). To access them everywhere outside function you need to declare it as global variable.
this would refer to the current DOM element h1 which invoked the event. Enclosing it with a $ makes it a jquery object. So $(this) basically refers to the jquery h1 object . So $(this) = $('h1') where h1 is the event which triggered the event.
$(this) is a jQuery wrapper around that element that enables usage of jQuery methods. jQuery calls the callback using apply() to bind this . Calling jQuery a second time (which is a mistake) on the result of $(this) returns an new jQuery object based on the same selector as the first one.
Variables declared Globally (outside any function) have Global Scope. Global variables can be accessed from anywhere in a JavaScript program. Variables declared with var , let and const are quite similar when declared outside a block.
A simpler way is to reference the function instead of wrapping it inside an anonymous one, like this:
$('.class').click(resetColor);
this
represents the context of who called the function. When you call resetColor
, it's implicitly using the top level this
which is the window
object. If you would like maintain context to through function calls, you can use call()
.
$('.class').click(function() {
resetColor.call(this);
});
The other obvious option is to not use this
, but rather pass the element as an argument.
function resetColor(e) {
$(e).css({color: 'red'});
}
$('.class').click(function() {
resetColor(this);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With