Experienced jQuery Interview Questions
What is event delegation in jQuery and why is it useful?
<ul id="list"><li>A</li></ul>
$('#list').on('click', 'li', function () { console.log('clicked ' + $(this).text()); });
$('#list').append('<li>B</li>'); // added later
$('#list li').eq(1).click();
clicked B
It saves memory (one handler) and works for dynamic content. See Event Delegation.
What is the difference between bind(), live(), delegate() and on() in jQuery?
| Method | Status |
|---|---|
.bind(event, fn) | Deprecated since 3.0, use .on() |
.live() | Removed in jQuery 1.9, was the delegated version for the document |
.delegate(sel, event, fn) | Deprecated since 3.0, use .on(event, sel, fn) |
.on() | The one method to use for direct and delegated events |
<p>Page</p>
console.log('on: ' + typeof $.fn.on + ', live: ' + typeof $.fn.live);
on: function, live: undefined
What is a callback function in jQuery and why is it needed in effects?
<div id="b">Box</div>
$('#b').hide(300, function () {
console.log('2. callback: effect finished');
});
console.log('1. this runs immediately after starting the effect');
2. callback: effect finished
1. this runs immediately after starting the effect
What is the difference between stop(), finish() and delay() in jQuery?
| Method | Meaning |
|---|---|
.stop() | Stops the current animation where it is. .stop(true) also clears the queue |
.stop(true, true) | Clears the queue and jumps the current animation to its end |
.finish() | Jumps all queued animations of the element to their end values |
.delay(ms) | Waits before the next item of the queue |
Use .stop(true) before a hover animation, so quick hovering does not pile up animations. See jQuery animate().
What are Deferred objects and promises in jQuery?
{ "n": 1 }
{ "n": 2 }
<p>Page</p>
$.when($.getJSON('a.json'), $.getJSON('b.json')).done(function (a, b) {
console.log('Sum: ' + (a[0].n + b[0].n));
});
Sum: 3
How do you handle Ajax errors in jQuery?
<p>Page</p>
$.getJSON('missing.json')
.done(function () { console.log('ok'); })
.fail(function (xhr, status, error) {
console.log('Failed: ' + xhr.status + ' ' + error);
})
.always(function () { console.log('Request finished'); });
Failed: 404 Not Found
Request finished
Also set a timeout, show a message to the user and log the details. See jQuery Ajax.
How do you create a jQuery plugin?
<p class="a">One</p><p class="a">Two</p>
$.fn.markAs = function (options) {
var settings = $.extend({ label: 'done' }, options);
return this.each(function () {
$(this).addClass(settings.label);
});
};
$('.a').markAs({ label: 'checked' });
<p class="a checked">One</p>
<p class="a checked">Two</p>
See jQuery Plugins.
What does jQuery.noConflict() do?
<p id="t">Text</p>
var $j = jQuery.noConflict();
console.log('$ is ' + typeof window.$);
$j('#t').text('Works with $j');
console.log($j('#t').text());
$ is undefined
Works with $j
WordPress loads jQuery in this mode, so scripts there use jQuery(...). See noConflict.
What are the main differences between jQuery 3 and jQuery 4?
<p>Page</p>
console.log('$.trim: ' + typeof $.trim);
console.log('$.isArray: ' + typeof $.isArray);
console.log('$.parseJSON: ' + typeof $.parseJSON);
jQuery 3.7.1:
$.trim: function
$.isArray: function
$.parseJSON: function
jQuery 4.0.0:
$.trim: undefined
$.isArray: undefined
$.parseJSON: undefined
Use the native JavaScript versions to make the code work in both. See jQuery 4 and Upgrading.
What is the difference between data() and attr(‘data-*’) in jQuery?
<div id="d" data-count="5"></div>
console.log(typeof $('#d').attr('data-count') + ' ' + $('#d').attr('data-count'));
console.log(typeof $('#d').data('count') + ' ' + $('#d').data('count'));
$('#d').data('count', 10);
console.log('after data(): attr = ' + $('#d').attr('data-count') + ', data = ' + $('#d').data('count'));
string 5
number 5
after data(): attr = 5, data = 10
What is the use of end() in jQuery?
<ul id="l"><li class="a">A</li><li class="b">B</li></ul>
$('#l')
.find('.a').addClass('first')
.end()
.find('.b').addClass('second');
<ul id="l">
<li class="a first">A</li>
<li class="b second">B</li>
</ul>
See Method Chaining.
How do you prevent XSS (cross-site scripting) when using jQuery?
<div id="out"></div>
var userInput = '<img src=x onerror=alert(1)>';
$('#out').text(userInput);
console.log($('#out').html());
console.log($('#out').find('img').length);
<img src=x onerror=alert(1)>
0
- Use
.text()or.val()for user data..html(),.append(string)and$(string)read HTML. - Create elements with
$('<li>').text(data). - Validate and escape on the server, and use a Content Security Policy.
How can you improve the performance of jQuery code?
- Save selections in variables (
var $box = $('#box');). - Use chaining and
.find()from a known parent. - Use event delegation for lists and dynamic content.
- Build HTML first and add it in one DOM change.
- Use classes (
addClass) instead of many.css()calls. - Limit the work in
scrollandresizehandlers. - Use the minified file, a CDN or cache, and load scripts at the end of the page.
See Best Practices.
What is the difference between width(), innerWidth() and outerWidth() in jQuery?
| Method | Includes |
|---|---|
width() | Content only |
innerWidth() | Content and padding |
outerWidth() | Content, padding and border |
outerWidth(true) | Content, padding, border and margin |
For a box with width 200, padding 10, border 5 and margin 20 on each side, they give 200, 220, 230 and 270. They need a real browser layout, so they return 0 in a test tool. See Dimensions and Position.