jQuery 'this' — Complete Guide to the Keyword in Event Handlers and Callbacks
In this tutorial, you will learn about jquery 'this'. We cover key concepts, practical examples, and best practices to help you master this topic.
The jQuery 'this' keyword refers to the current DOM element in event handlers and callbacks, providing direct access to the element without a jQuery wrapper for better performance and clarity.
What You'll Learn
- What 'this' refers to in different jQuery contexts
- Converting 'this' to a jQuery object with $(this)
- 'this' in event handlers, each loops, and callbacks
- Arrow functions vs function expressions with 'this'
- Common pitfalls and best practices
Why It Matters
Understanding 'this' is critical for correct jQuery code. Misunderstanding the context leads to bugs where you operate on the wrong element, call methods that do not exist, or get undefined errors.
Real-World Use
A table with editable cells. Clicking a cell highlights it, double-clicking makes it editable, and pressing Enter saves the value. Each handler uses 'this' to identify and manipulate the clicked cell without re-selecting it.
'this' Context Flow
flowchart TD
A[Code Context] --> B{Where is this?}
B -->|Event Handler| C[DOM Element]
B -->|$.each callback| D[Current Array Item]
B -->|$.each element| E[DOM Element]
B -->|Method call| F[Object before dot]
B -->|Arrow function| G[Outer Context]
style C fill:#e6f3ff,stroke:#4a90d9,stroke-width:2px
'this' in Event Handlers
In jQuery event handlers, this refers to the DOM element that received the event:
$('.item').on('click', function() {
// 'this' is the clicked DOM element
console.log(this); // <div class="item">...</div>
console.log(this.tagName); // DIV
// Convert to jQuery object for jQuery methods
$(this).addClass('active');
$(this).css('background', '#3498db');
});
// Multiple events
$('input').on({
focus: function() {
$(this).addClass('focused');
},
blur: function() {
$(this).removeClass('focused');
validateField($(this));
}
});
Expected output: In the click handler, this is the exact DOM element clicked. Wrapping with $(this) enables jQuery methods.
'this' vs $(this)
$('.item').click(function() {
// 'this' — raw DOM element
this.style.color = 'red'; // Native JS (faster)
console.log(this.id); // Native property access
// $(this) — jQuery wrapper
$(this).css('color', 'red'); // jQuery method (convenient)
$(this).addClass('highlight');
$(this).data('key', 'value');
// Mixing is fine, but be consistent within a handler
var $el = $(this); // Cache at start of handler
$el.addClass('clicked');
console.log($el.data('id'));
});
'this' in $.each()
In $.each(), this refers to the current element or value:
// Iterating an array
$.each(['apple', 'banana', 'cherry'], function(index, value) {
console.log(this === value); // true — 'this' is the current value
console.log(this); // 'apple', then 'banana', then 'cherry'
});
// Iterating jQuery collection
$('.item').each(function(index) {
// 'this' is the current DOM element
console.log(this); // DOM element
console.log($(this).text()); // Element's text
// Store index as data
$(this).data('index', index);
});
'this' in Callbacks
// Animation callback
$('.box').slideUp(400, function() {
// 'this' is the animated DOM element
$(this).css('display', 'none');
console.log('Animation finished for', this.id);
});
// AJAX callback (depends on context option)
$.ajax({
url: '/api/data',
context: document.body, // 'this' will be document.body
success: function(data) {
console.log(this === document.body); // true
$(this).append('<p>Data loaded</p>');
}
});
'this' in Arrow Functions
Arrow functions do NOT have their own this — they inherit from the enclosing scope:
// BAD: Arrow function changes 'this' context
$('.item').click(() => {
// 'this' is NOT the DOM element — it's the outer scope (likely window)
$(this).addClass('active'); // Wrong element!
});
// GOOD: Regular function expression
$('.item').click(function() {
$(this).addClass('active'); // Correct — 'this' is the clicked element
});
// GOOD: Arrow function inside $.each (outer scope preserved)
var self = this;
$('.item').each(function() {
// 'this' is the DOM element (regular function)
// 'self' is the outer object
});
'this' in Custom Methods
var MyWidget = {
init: function() {
this.name = 'Widget'; // 'this' is MyWidget
$('.btn').click(this.handleClick);
},
handleClick: function() {
// 'this' is the DOM element (button), not MyWidget!
console.log(this.name); // undefined
}
};
// Fix: use $.proxy or bind
var MyWidget = {
init: function() {
this.name = 'Widget';
$('.btn').click($.proxy(this.handleClick, this));
// OR: $('.btn').click(this.handleClick.bind(this));
},
handleClick: function() {
// 'this' is now MyWidget
console.log(this.name); // Output: Widget
}
};
// Modern fix: arrow function in the click handler
var MyWidget = {
init: function() {
this.name = 'Widget';
$('.btn').click((e) => {
// 'this' is MyWidget (arrow inherits from init's 'this')
console.log(this.name); // Widget
// For the DOM element, use e.target
console.log(e.target);
});
}
};
'this' in Event Delegation
$('.list').on('click', '.item', function() {
// 'this' is the .item element that was clicked
// Not the .list container
$(this).toggleClass('selected');
});
// Access the delegate (container)
$('.list').on('click', '.item', function(e) {
var $item = $(this);
var $list = $(e.delegateTarget); // The .list container
var $relatedTarget = $(e.target); // The exact clicked element
});
Caching $(this) for Performance
// BAD: Re-wrapping $(this) multiple times
$('.item').click(function() {
$(this).addClass('active');
$(this).data('clicked', true);
$(this).find('.child').toggle();
});
// GOOD: Cache $(this) once
$('.item').click(function() {
var $this = $(this);
$this.addClass('active');
$this.data('clicked', true);
$this.find('.child').toggle();
});
Common Mistakes
Using arrow functions in event handlers - Arrow functions inherit
thisfrom the outer scope, not the DOM element. Always usefunction()for event handlers.Assuming 'this' in $.ajax success is the element - By default,
thisin AJAX callbacks is the Ajax settings object. Usecontextoption or arrow functions.Forgetting to wrap 'this' for jQuery methods -
this.addClass('active')throws an error becausethisis a DOM element, not a jQuery object. Use$(this).addClass().'this' in nested callbacks - Inside a forEach, map, or setTimeout,
thischanges. Capture the outerthisin a variable:var self = this.Confusing 'this' and event.target -
thisis the element the handler is bound to.event.targetis the element that triggered the event. They differ in event delegation.
Practice Questions
- What does 'this' refer to inside a jQuery click handler?
- Why should you avoid arrow functions in jQuery event handlers?
- How do you convert 'this' to a jQuery object?
- What is the difference between 'this' and event.target?
- How do you preserve the outer 'this' inside a $.each loop?
Challenge: Build a tooltip plugin where hovering over any element with a data-tooltip attribute shows a tooltip. Use 'this' correctly in the hover handlers, cache $(this), and handle the tooltip positioning relative to 'this'.
FAQ
Mini Project
Build a drag-and-drop card game where clicking a card selects it, clicking another position moves it. Each handler uses 'this' to identify the clicked card. Cache $(this) at the start of each handler for performance.
What's Next
The 'this' keyword is fundamental. Learn how jQuery event handling uses 'this' to connect user interactions with element-specific logic.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro