Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use $(this) in an outside function

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.

like image 468
yuvalsab Avatar asked Aug 22 '14 22:08

yuvalsab


People also ask

How use jQuery variable outside function?

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.

When we should use $( this in jQuery?

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.

What does $( this mean in jQuery?

$(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.

Can we access variable outside function in JavaScript?

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.


2 Answers

A simpler way is to reference the function instead of wrapping it inside an anonymous one, like this:

$('.class').click(resetColor);
like image 173
omma2289 Avatar answered Sep 30 '22 16:09

omma2289


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);
});
like image 32
Austin Brunkhorst Avatar answered Sep 30 '22 15:09

Austin Brunkhorst