$('button').on('click', function () {
alert('you clicked the button!');
});
$('button').click(function () {
alert('you clicked the button!');
});
.on..click(function) is shorter way to write .on('click', function).jQuery('p')
<button class="btn btn-primary" type="submit">Continue to checkout</button>
$('.btn-primary').toggle();$('.btn-primary').showHide();$('.btn-primary').not(':visible').show();$('.btn-primary').css({ display: 'block'});https://example.com/json-api/students
https://example.com/json-api/classes
$.get(
['https://example.com/json-api/students', 'https://example.com/json-api/classes'],
function (studentRequest, classRequest) {
// the rest of the code goes here
},
);
$.when(
$.get('https://example.com/json-api/students'),
$.get('https://example.com/json-api/classes'),
).done(function (studentRequest, classRequest) {
// the rest of the code goes here
});
$.bind(
$.get('https://example.com/json-api/students'),
$.get('https://example.com/json-api/classes'),
).done(function (studentRequest, classRequest) {
// the rest of the code goes here
});
$.ajax('https://example.com/json-api/students', {
success: function (studentRequest) {
$.ajax('https://example.com/json-api/classes', {
success: function (classRequest) {
// the rest of the code goes here
},
});
},
});
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
$('ul').find('li').get(2);
$('ul').find('li').eq(2);
$('#ball').click(function () {
// Our code goes here
});
$(this).animate(
{ top: '+=100', left: '+=100' },
{
duration: 600,
complete: function () {
$(this).animate({ top: '-=100', left: '-=100' }, 600);
},
},
);
$(this).animate({ top: '-=100', left: '-=100' }, 600, function () {
$(this).animate({ top: '+=100', left: '+=100' }, 600);
});
$(this).animate(
{ top: '=100', left: '=100' },
{
duration: 600,
complete: function () {
$(this).animate({ top: 0, left: 0 }, 600);
},
},
);
$(this).animate({ top: '100', left: '100' }, 600, function () {
$(this).animate({ top: 0, left: 0 }, 600);
});
.success {
color: green;
background: #ddffdd;
}
<div class="feedback">Thank you for answering this survey.</div>
$('.feedback').hasClass('.success');$.css('.feedback', '.success');$('.feedback').addClass('success');$('.feedback').css('.success');<div class="message-area">
<ul class="message-area--list">
<li>Existing message 1</li>
<li>Existing message 2</li>
</ul>
</div>
$.get('//example.com/api/v1/message').done(function (data) { var tonsOfItems = data.messages; // add
all these messages to a large page });
tonsOfItems.map(function (item) {
$('.message-area--list').append('<li>' + item + '</li>');
});
var tonsOfListItems = tonsOfItems.map(function (item) {
return '<li>' + item + '</li>';
});
$('.message-area--list').append(tonsOfListItems.join(''));
CSS.$messageList = $('.message-area--list');
$.each(tonsOfItems, function (idx, item) {
$('<li>' + item + '</li>').appendTo($messageList);
});
$.each(tonsOfItems, function (idx, item) {
$('.message-area--list').append('<li>' + item + '</li>');
});
'user strict';
($.linkUpdater = function () {
this.find('a').attr('target', '_blank');
})(jQuery);
$(this), in order to be chained in a plugin.<button class="btn btn-primary" type="submit">Continue to checkout</button>
$('.btn-primary').hide();$('.btn-primary:visible').not();$('.btn-primary').visibility(false);$('.btn-primary').show(false);$('header').html() and $('header').text()?$('header').html() returns the inner HTML of the header. $('header').text() returns only the text$('header').html() returns only the HTML tags used, without the text. $('header').text() returns only the text$('header').html() strips all HTML from the header. $('header').text() always returns an empty string.$('header').html() returns all headers in an HTML document. $('header').text() the first line of a text file.<article>
<div>Here's a button you can click: <button class="btn">Click Me</button></div>
<form>
<p>Further down the page, there's a select box.</p>
<select>
<option value="1">One</option>
<option value="2">One</option>
<option value="3">One</option>
<option value="4">One</option>
</select>
</form>
</article>
$('button').on('click.myApp', (function() { $('input[type=select]').trigger('click'); });$('button').on('click', (function() { $('input[type=select]').click()); });$('button').trigger(function() { $('input[type=select]').click(); });$('button').click(function() { $('input[type=select]').click(); });.animate-me?<style>
.parent {
position: relative;
top: 3em;
width: 50%;
min-height: 50vh;
margin: 0 auto;
}
.animate-me {
position: absolute;
top: 40px;
right: 30px;
}
</style>
<div class="parent">
<div class="animate-me">This box will move!</div>
</div>
$('.animate-me').offset();$('.animate-me').each();$('.animate-me').position();$('.animate-me').offsetParent();jQuery.subjQuery.ajaxTransportjQuery.DeferredjQuery.proxydocument.querySelectorAll.$.get('http://httpbin.org/delay/2')
.then(function (response) {
// Data from first GET is here as 'response'
return $.get('http://httpbin.org/delay/2');
})
.then(function (response) {
// Data from second GET is here as 'response'
});
$.get('http://httpbin.org/delay/2')
.catch(function (response) {
// Data from first GET is here as 'response'
return $.get('http://httpbin.org/delay/2');
})
.done(function (response) {
// Data from second GET is here as 'response'
});
$.get('http://httpbin.org/delay/2', function (response1) {
// Data from first GET is here as 'response1'
$.get('http://httpbin.org/delay/2', function (response2) {
// Data from second GET is here as 'response2'
});
});
$.get('http://httpbin.org/delay/2')
.then(function (response) {
// Data from first GET is here as 'response'
return response;
})
.get('http://httpbin.org/delay/2', function (response) {
// Data from second GET is here as 'response'
});
$('#ball').click(function () {
// Our code goes here
});
$(this).animate(
{
top: '-=100',
left: '-=100',
},
600,
function () {
$(this).animate(
{
top: '+=100',
left: '+=100',
},
600,
);
},
);
$(this).animate(
{
top: '+=100',
left: '+=100',
},
{
duration: 600,
complete: function () {
$(this).animate(
{
top: '-=100',
left: '-=100',
},
600,
);
},
},
);
$(this).animate(
{
top: 100,
left: 100,
},
600,
function () {
$(this).animate(
{
top: 0,
left: 0,
},
600,
);
},
);
$(this).animate(
{
top: 100,
left: 100,
},
{
duration: 600,
complete: function () {
$(this).animate(
{
top: 0,
left: 0,
},
600,
);
},
},
);
.wrap() works is sometimes misunderstood. Given the DOM and jQuery snippets below, what does the modified DOM snippet look like?<div id="container">
<div class="item">Here's an item</div>
</div>
$('#container').wrap('<div class="wrapper"></div>').css('border', '2px solid red');
<div class="wrapper" style="border: 2px solid red;">
<div id="container">
<div class="item">Here's an item</div>
</div>
</div>
<div class="wrapper">
<div id="container" style="border: 2px solid red;">
<div class="item">Here's an item</div>
</div>
</div>
<div id="container" style="border: 2px solid red;">
<div class="wrapper">
<div class="item">Here's an item</div>
</div>
</div>
<div id="container">
<div class="wrapper" style="border: 2px solid red;">
<div class="item">Here's an item</div>
</div>
</div>
<div class="quotes">
<blockquote data-favorite="false">A quote</blockquote>
<blockquote data-favorite="true">A favorite quote</blockquote>
<blockquote data-favorite="false">A quote</blockquote>
<blockquote data-favorite="false">A quote</blockquote>
</div>
<ul class="menu-first">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
$('.quotes + .menu-first')$('.quotes .menu-first')$('.quotes, .menu-first')$('.quotes' + '.menu-first')$('#dialog').classToggle('bounce')$('#dialog.bounce').removeClass().addClass()$('#dialog').addOrRemoveClass('bounce')$('#dialog').toggleClass('bounce')$('#canvas').on('click.right', function(){ console.log('Handled a right-click') });$('#canvas').on('contextual', function(){ console.log('Handled a right-click') });$('#canvas').on('contextmenu', function(){ console.log('Handled a right-click') });$('#canvas').on('rightclick', function(){ console.log('Handled a right-click') });$('p').count()$('p').length$('*').find('p')$('p').length()this is important and sometimes tricky. What does this mean at each of the two points in this custom plugin snippet?$.fn.customPlugin = function () {
// Point 1
return this.each(function () {
// Point 2
});
};
$(document).customPlugin();
this means a jQuery object. At Point 2, it means a DOM element.this means a DOM element. At Point 2, it means a jQuery object.<ul class="menu-first">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
$('.menu-first > li').eq(0).css('font-weight', 'bold').eq(1).css('font-style', 'oblique');
$('.menu-first > li').first().css('font-weight', 'bold').after().css('font-style', 'oblique');
$('.menu-first > li').first().css('font-weight', 'bold').second().css('font-style', 'oblique');
$('.menu-first > li').eq(0).css('font-weight', 'bold').next().css('font-style', 'oblique');
.class1.class2.:not or :last-of-type.#element.class..leaf is clicked, only its event handler will be fired, instead of the click bubbling up and also firing the parent’s click handler. What do you need to add to its handler function?<ul class="items" id="main-menu">
<li>
Item 1
<ul>
<li class="leaf">Sub Item 1</li>
<li>Sub Item 2</li>
</ul>
</li>
</ul>
$('.leaf').click(function (event) {
console.log('Sub Item 1 got a click');
});
$('#main-menu').click(function (event) {
console.log('Main menu got a click');
});
event.capture();event.stopPropagation();event.preventDefault();event.stop();Difference between preventDefault, stopPropagation & return false
<div id="sidebar">
<img src="fancy-button.png" alt="Pick Me" />
<input type="text" placeholder="Fill in something" />
</div>
$('#sidebar').click(function (evt) {
var $target = $(evt.target);
// What goes here?
});
$($target.get(0) + ':image')$('img').is($target)$target.filter('img')$target.is('img')<div id="elements"></div>
$('#elements').append($('<p class="appended">As an HTML string</p>'));
var p = document.createElement('p');
var text = document.createTextNode('As a DOM element');
p.appendChild(text);
$('#elements').append(p);
$('#elements').append(<p class="appended">As a JSX object</p>);
$('#elements').append(
$('<p>', {
class: 'appended',
text: 'As an attribute object',
}),
);
.addClass() and .removeClass() methods can accept functions as arguments. What does this function do?$('#menu').addClass(function () {
return $('body').attr('class');
});
jQuery.noConflict() on pages that need the older version.$('a').attribute('href', 'http://www.example.com')$('a').attr('href', 'http://www.example.com')$('a').data('href', 'http://www.example.com')$('a').href('http://www.example.com')$() mean in jQuery?document.getElementById().jQuery.each, a general purpose iterator for looping over arrays or objectsjQuery.isNumeric, which can check whether its argument is, or looks like, a numberjQuery.extend, which can merge objects and make complete deep copies of objectsjQuery.isMobile, which can tell whether the user is using a mobile browser<input type="checkbox" name="artists[]" value="sun-ra" />
<input type="checkbox" name="artists[]" value="otis-redding" />
<input type="checkbox" name="artists[]" value="captain-beefheart" />
<input type="checkbox" name="artists[]" value="king-sunny-ade" />
<input type="checkbox" name="artists[]" value="weather-report" />
$('checkbox').val(/sun/);$('input[value*="sun"]');$('input[value|="sun"]');$('input:checkbox').attr('value', '*sun*');.form-item to “555-1212”?$.val('.form-item', '555-1212');$('.form-item').val('555-1212');$('.form-item').data('value', '555-1212');$('.form-item').set('value', '555-1212');$('body').ajaxComplete(function() { console.count('An AJAX request completed'); });$(document).on('ajax-complete', function() { console.count('An AJAX request completed'); });$('body').on('ajaxComplete', function() { console.count('An AJAX request completed'); });$(document).ajaxComplete(function() { console.count('An AJAX request completed'); });Source: ajaxComplete
Explanation: Note: As of jQuery version 1.8, this method should only be attached to document.
<input type="checkbox" name="songs[]" value="satisfaction" />
<input type="checkbox" name="songs[]" value="respect" />
<input type="checkbox" name="songs[]" value="blimp" />
<input type="checkbox" name="songs[]" value="saturn" />
<input type="checkbox" name="songs[]" value="penguins" />
$('input[value="blimp"]');$('input[value!="blimp"]');$('checkbox').val('blimp');$('input:checkbox').attr('value', 'blimp');<ul class="menu">
<li><a href="#" class="active">Home</a></li>
<li><a href="#">Page 2</a></li>
</ul>
<ul class="active submenu">
<li><a href="#">Subpage 1</a></li>
<li><a href="#">Subpage 2</a></li>
</ul>
var m = $('.menu'),
sm = $('.submenu');
m.add(sm);
m.css('font-weight', 'bold');
<div id="type" style="font: 1em/1.5 helvetica, arial, sans-serif; background: #ffc; padding: 0">
Animate me!
</div>
$('#type').animate(
{
fontSize: '+=1em',
},
3000,
);
clone() function to duplicate an element, what is one of the main concerns your code needs to watch out for?clone() function may ignore data attributes on the original elements.clone() function may result in elements with duplicate ID attributes.clone() function may remove CSS classes from the cloned elements.clone() function may not respect the attribute order of the original elements.<head>, followed by jQuery, followed by the plugin.<head>, and your custom scripts can follow anywhere on the page.<head>, but the plugin and your custom scripts can appear anywhere else in any order.ready() method. What is true about both approaches?<script>
$(function() {
// The rest of my code goes here
});
</script>
<script>
jQuery(document).ready(function($) {
// The rest of my code goes here
});
</script>
$('.item').css('background-color', 'red');
// some other code here
var firstSubItem = $('.item').find('.sub-item').get(0);
// some other code here too
$('.item').parents('.navigation').css('font-weight', 'bold');
.css() method accepts only an object, not two separate arguments. This will trigger an exception that should be caught.$('.item') selection is being made several times. This should be cached in a variable for (however slightly) better performance and easier maintainability..parents() is in an inefficient place.$('.item') should be chained together as a single executable line for better performance.var $p = $('p'); console.log($p.length);$('p').find('a').children('li');$('p > a > li');$('p'); $('a'); $('li');active appears on an element?$('.element').attr('class', 'active')$('.element').with('.active')$('.element').hasClass('active')$('.active').then()load() that make calling that main function easier. Given this HTML snippet, how can you insert only the second snippet from the source.html file (div#one) into the #load-me div on-demand via AJAX?<div id="load-me">This area will be replaced with AJAX loaded content.</div>
<div id="one">
<h1>First Piece</h1>
<p>Lorem ipsum duis maximus quam condimentum dolor eleifend scelerisque.</p>
</div>
<div id="two">
<h1>Second Piece</h1>
<p>Lorem ipsum proin facilisis augue in risus interdum ornare.</p>
</div>
$('#load-me').get('source.html#one');$('#load-me').get('source.html #one');$('#load-me').load('source.html #one');$('#load-me').load('source.html', '#one');.closest() and .parents()?<ul class="items" id="main-menu">
<li>
Item 1
<ul id="sub-menu">
<li class="leaf">Sub Item 1</li>
<li>Sub Item 2</li>
</ul>
</li>
</ul>
$('.leaf').closest('.items');
$('.leaf').parents('.items');
.closest() returns .leaf and #main-menu; .parents() returns #main-menu and #sub-menu..closest() returns .leaf and #sub-menu; .parents() returns #main-menu and #sub-menu..closest() returns only #main-menu; .parents() returns #main-menu and #sub-menu..closest() returns only #sub-menu; .parents() returns #main-menu and #sub-menu.Explanation: Considering current HTML code, .closest() returns only #main-menu; .parents() returns only #main-menu; cause both of them are looking for .items class which only exist in the #main-menu. Thus all choices are incorrect. This can be seen using this snippet: $('.leaf').closest('.items').each(function(i, obj) {console.log(obj)}); $('.leaf').parents('.items').each(function(i, obj) {console.log(obj)});
$('ul > li:first-child');
<ul class="clickable-list">
<li>First Item</li>
<li>Second Item</li>
<li>Third Item</li>
<li>Fourth Item</li>
<li>Fifth Item</li>
</ul>
function listResponder(evt) {
console.log('You clicked a list item that says', evt.target.innerText);
}
$('.clickable-list').click(listResponder);$('.clickable-list').on('click', 'li', listResponder);$('.clickable-list').on('click, append', listResponder);$('.clickable-list').each(function() { $(this).click(listResponder); });find() traverses only one level down, whereas children() selects anything inside the original element$('p').find('a') finds all paragraphs inside links, whereas $('p').children('a') finds links within paragraph tags.find() always searches the entire DOM tree, regardless of the original selection .children() searches only the immediate childern of an elementchildren() traverses only one level down, whereas find() selects anything inside the original elementSource: https://api.jquery.com/find/
Explanation:Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.
<div class="balls">
<div class="ball ball--red" style="display: none"></div>
<div class="ball ball--green" style="display: none"></div>
<div class="ball ball--blue" style="display: none"></div>
</div>
$('.ball--green').fadeIn(3000, function(){
console.log("Animation is done!");
});
$('.ball--green').fade('in',3000).done(function(){
console.log("Animation is done!");
});
$('.ball--green').fadeIn(3).console().log("Animation is done!");
$('.ball--green').fadeIn("3s", function(){
console.log("Animation is done!");
});
Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively. If any other string is supplied, or if the duration parameter is omitted, the default duration of 400 milliseconds is used.
$(document).on('myCustomEvent', function(){
// act on my custom event
});
//and later...
$(document).trigger('myCustomEvent');
Custom events are at least an order of magnitude faster than helper functionsCustom events can be listened for and acted upon across one or more scripts without needing to keep helper functions in scopeHandler functions for custom events are less likely to be mangled by minification and obfuscation build toolsIt is easier to write documentation for custom events than it is for helper functionsInstead of focusing on the element that triggers an action, custom events put the spotlight on the element being acted upon. This brings a bevy of benefits, including: Behaviors of the target element can easily be triggered by different elements using the same code. Behaviors can be triggered across multiple, similar, target elements at once. Behaviors are more clearly associated with the target element in code, making code easier to read and maintain.
<div id="element-1" class="animel"></div>
<div id="element-2" class="animel"></div>
<div id="element-3" class="animel"></div>
$('#element-1').animate({ top: '+=100' }); $('#element-2').animate({ top: '+=100' });
$('#element-3').animate({ top: '+=100' });
$('#element-1').animate({ top: '+=100' })
.pushStack('#element-2')
.animate({ top: '+=100' })
.pushStack('#element-3').animate({ top: '+=100' })
$('#element-1').animate({ top: '+=100' }, function() {
$('#element-2').animate({ top: '+=100' }, function() {
$('#element-3').animate({ top: '+=100' });
})
});
$('#element-1').animate({ top: '+=100' })
.add('#element-2').animate({ top: '+=100' })
.add('#element-3').animate({ top: '+=100' })
$('#element-1').animate({ top: '+=100' }, {queue: 'custom'});
$('#element-2').animate({ top: '+=100' }, {queue: 'custom'});
$('#element-3').animate({ top: '+=100' }, {queue: 'custom'});
$('custom').dequeue();
the .animate() method can take in a function to call once the animation is complete, called once per matched element. Which is called the complete option for the animate method
<input type="checkbox" id="same-address" checked>
$('#same-address').val()$('#same-address').prop('checked')$('#same-address').attr('checked')$('#same-address').checkedjQuery.version()jQuery.jqueryjQuery.prototype.versionjQuery.fn.jquery<input type="text" class="form-control" id="firstName" placeholder="" value="" required="">
$('input[type=text]').val()$('.form-control').val()all of these answers$('#firstName').val()all the listed selectors will target the text field since it has a type=text, a class=form-control, and an id=firstName
Source: jQuery Docs: event.target
The target property can be the element that registered for the event or a descendant of it. It is often useful to compare event.target to this in order to determine if the event is being handled due to event bubbling.
Extra reading: Event Bubbling and capturing
$.fn.myTraverse = function() {
// ... setup
var additionalItems = [ /* some additional items for jQuery */ ];
return // return what?
}
return this.append(additionalItems);return additionalItems.appendTo(this);return this.pushStack(additionalItems);return this.add(additionalItems);When you call pushStack() off of the current collection, it will take the given collection and associate it to the current collection such that calling the end() method (after the plugin exits) will return the programmer to the current collection.
<ul class="items">
<li class="active">Item 1</li>
<li>Item 2</li>
<li>
Item 3
<ul>
<li>Sub Item 1</li>
<li>Sub Item 2</li>
</ul>
</li>
</ul>
$('.items').find('.active').nextAll().addClass('after-active');
<ul class="items">
<li class="active">Item 1</li>
<li class="after-active">Item 2</li>
<li class="after-active">
Item 3
<ul>
<li>Sub Item 1</li>
<li>Sub Item 2</li>
</ul>
</li>
</ul>
<ul class="items">
<li class="active">Item 1</li>
<li class="after-active">Item 2</li>
<li class="after-active">
Item 3
<ul class="after-active">
<li>Sub Item 1</li>
<li>Sub Item 2</li>
</ul>
</li>
</ul>
<ul class="items">
<li class="active">Item 1</li>
<li class="after-active">Item 2</li>
<li class="after-active">
Item 3
<ul>
<li class="after-active">Sub Item 1</li>
<li class="after-active">Sub Item 2</li>
</ul>
</li>
</ul>
<ul class="items">
<li class="active">Item 1</li>
<li class="after-active">Item 2</li>
<li class="after-active">
Item 3
<ul class="after-active">
<li class="after-active">Sub Item 1</li>
<li class="after-active">Sub Item 2</li>
</ul>
</li>
</ul>
.nextAll([selector]) method
Gets all following siblings of each element in the set of matched elements, optionally filtered by a selector.
$('#element').on('animationend', function () {
console.log('Finally, everything is done!');
});
$('#element')
.on('promise')
.then(function () {
console.log('Finally, everything is done!');
});
$('#element')
.promise()
.catch(function () {
console.log('Finally, everything is done!');
});
$('#element')
.promise()
.then(function () {
console.log('Finally, everything is done!');
});
| [Source: HTMLElement: animationend event | MDN ](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/animationend_event) |
Explanation: Although A is not complete as it could include animationend webkitAnimationEnd oAnimationEnd, other choices are incorrect. The last choice could be also correct if it were .promise().done instead
<div class="quotes">
<blockquote data-favorite="false">A quote</blockquote>
<blockquote data-favorite="false">A favorite quote</blockquote>
<blockquote data-favorite="false">A quote</blockquote>
<blockquote data-favorite="false">A quote</blockquote>
</div>
$('blockquote'):second().attr('favorite', true);$('blockquote:nth-child(2)').data('favorite', true);$('blockquote').second().data('favorite', true);$('blockquote:nth-child(2)').attr('favorite', true);| [Source: .data() | jQuery API Documentation](https://api.jquery.com/data/) |
| [Source: :nth-child() | MDN Docs](https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child) |
$('button').click(function() { console.log('this will only happen once'); }, false);$('button').on('click', function() { console.log('this will only happen once'); }).off('click');$('button').once('click', function() { console.log('this will only happen once'); });$('button').one('click', function() { console.log('this will only happen once'); });| [Source: .one() | jQuery API Documentation](https://api.jquery.com/one/) |
slideDown() manually using animate(). What is one critical point you need to remember?slideDown() requires animating the background color; doing so with animate() requires the jQuery Color plugin.slideDown() includes toggling visibility automatically. animate() does not automatically set any properties.slideDown() requires the element to have a height set in pixels. animate() does not.animate() must be run over at least 100 milliseconds, where slideDown() can run as quickly as 50ms.| [Source: .slideDown() | jQuery API Documentation](https://api.jquery.com/slidedown/) |
| [Source: .animate() | jQuery API Documentation](https://api.jquery.com/animate/)\ |
contents() and children() functions?children() also includes text and comment nodes.contents() function only includes text nodes of the selected elements.children() function only includes text nodes of the selected elements.contents() also includes text and comment nodes.| [Source: .children() | jQuery API Documentation](https://api.jquery.com/children/) |
| [Source: .contents() | jQuery API Documentation](https://api.jquery.com/contents/) |
.ready() function is one of the most basic parts of jQuery, but jQuery also provides a mechanism for executing code when both one or more Promises have resolved and the DOM is ready. Which code snippet accomplishes this?$(function({
getData : $.get('http://httpbin.org/get'),
delayedData : $.get('http://httpbin.org/delay/3')
}) {
//DOM is ready, getData and delayedData are available
});
$($.get('http://httpbin.org/get'), $.get('http://httpbin.org/delay/3')).then(
function (getData, delayedData) {
//DOM is ready, getData and delayedData are available
},
);
$.when($.get('http://httpbin.org/get'), $.get('http://httpbin.org/delay/3')).then(
function (getData, delayedData) {
//DOM is ready, getData and delayedData are available
},
);
$.ready($.get('http://httpbin.org/get'), $.get('http://httpbin.org/delay/3')).then(
function (getData, delayedData) {
//DOM is ready, getData and delayedData are available
},
);
// what goes here?
// ... do some other hidden work on $example
$example.prependTo(document.body);
var $example = $('#example').remove();var $example = $('#example').clone();var $example = $('#example').detach();var $example = $('#example').addBack().empty();https://api.jquery.com/detach/
<ul class="items">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li class="active">Item 4</li>
<li>Item 5</li>
<li>Item 6</li>
</ul>
$('.items > li').first().fadeOut().nextUntil('.active').fadeTo('fast', 0.5);
$('.items').children(':first-child').fadeOut().filter('.active').fadeTo('fast', 0.5);
$('.items > li').first().fadeOut().nextAll('.active').fadeOut(50);
$('.items').find('li:first-child').fadeOut().next('.active').fadeTo('fast', 0.5);
Source: jQuery.fx.off Property
$(document.body) first, then use .filter with the custom extension..has()..find with a selector that exists in CSS to limit the selection..filter() with the custom extension.Explanation: Special builds can be created that exclude subsets of jQuery functionality. This allows for smaller custom builds when the builder is certain that those parts of jQuery are not being used.
<ul class="menu">
<li><a href="#" class="active">Home</a></li>
<li><a href="#">Page 2</a></li>
</ul>
<ul class="active submenu">
<li><a href="#">Subpage 1</a></li>
<li><a href="#">Subpage 2</a></li>
</ul>
$('.menu').find('a').css('color', 'red').end().find('.active').hide();
<nav id="main">
<ul>
<li><a href="/" class="active">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
</nav>
$('a.active').addClass('hover');
http://example.com/api/v1 and you want to use custom events to ping that API from various places throughtout your codebase, what would that look like?// listens
$('body').on('myEvent', function () {
$.get('http://example.com/api/v1/ping');
});
// triggers
$('body').trigger('myEvent');
// listens
$('body').on('custom', 'myEvent', function () {
$.get('http://example.com/api/v1/ping');
});
// triggers
$('document').trigger('custom', 'myEvent');
// listens
$('body').on(function (event) {
if (event === 'myEvent') {
$.get('http://example.com/api/v1/ping');
}
});
// triggers
$('body').triggerHandler('myEvent');
// listens
$.on('myEvent', function () {
$.get('http://example.com/api/v1/ping');
});
// triggers
$.trigger('myEvent');
Source: Introducing Custom Events
<form> and </form> below, what does the snippet between <script> and </script> do?<form class="needs-validation" novalidate="">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="checkbox-opt-in">
<label class="custom-control-label" for="checkbox-opt-in">I totally read and accept the terms, really.</label>
</div>
</form>
<script>
$(function() {
$('form').submit(function(evt) {
if ($(this).find('.checkbox-opt-in').prop('checked') === false) {
evt.preventDefault();
alert("Please read and accept the terms.")
}
});
});
</script>
this). If the checkbox is selected, the form is allowed to submit.<div class="actions">
<a href="//example.com/action">Let's go!</a>
</div>;
var data = {
username: 'jaffacakes',
message: {
date: '2018-07-05 13:14:00 GMT-07:00',
text: `I have a whole lot to say, everyone, and I'm gonna say it!`,
},
tags: ['discourse', 'thoughts', 'messageOfTheDay'],
};
//example.com/action?username=jaffacakes&message%5Bdate%5D=2018-07-05+13%3A14%3A00+GMT-07%3A00
$(data).serializeArray();$.param(data, false);$.param(data, true);$(data).serialize();.wrap() and .wrapAll()?.wrap() wraps each element separately, while .wrapAll() requires at least two elements to work..wrap() wraps each matched element individually, while .wrapAll() wraps all matched elements together in a single wrapper..wrap() can only wrap one element, while .wrapAll() can wrap multiple elements.Source: .wrap() and .wrapAll()
.end() method do?$('ul.first')
.find('.foo')
.css('background-color', 'red')
.end()
.find('.bar')
.css('background-color', 'green');
.promise() without arguments versus .promise('fx')?.promise() returns immediately, while .promise('fx') waits for animations to complete..promise() returns a promise resolved when all animations on all matched elements complete, while .promise('fx') explicitly waits for the FX queue..promise() is used for AJAX, while .promise('fx') is used for animations..slideToggle() and .slideUp() / .slideDown() combined?// Option A
$('.element').slideToggle();
// Option B
if ($('.element').is(':visible')) {
$('.element').slideUp();
} else {
$('.element').slideDown();
}
.slideToggle() only works on elements that are already visible..slideToggle() is just a shorthand for the if/else block..slideToggle() tracks the current state internally and toggles based on visibility, while the manual approach may have issues with display styles..slideToggle() is deprecated and the manual approach should be used instead.<div class="container">
<p>Some text</p>
<div class="nested">
<p>More text</p>
</div>
</div>
$('.container').find('p')$('.container p')$('p', '.container')Source: .find() - Using .find() is more explicit and can be better for performance when working with large documents.
.stop() method do when called with no arguments versus .stop(true, true)?.stop() pauses the animation, .stop(true, true) completely removes it from the queue..stop() stops the current animation on the element, .stop(true, true) clears the queue and jumps to the end of the current animation..stop() is a deprecated method, .stop(true, true) is the new syntax.<div class="container">
<button class="dynamic-btn">Click me</button>
</div>
$('.dynamic-btn').on('click', function() { console.log('clicked'); }); - This works automatically for dynamic elements.$(document).on('click', '.dynamic-btn', function() { console.log('clicked'); }); - Delegated event handler.$('.dynamic-btn').live('click', function() { console.log('clicked'); }); - The .live() method.Source: .on() - Event delegation is key for dynamic elements.
$('#element').off().empty().removeData();$('#element').unbind().removeData();$('#element').detach();Source: .off() and .removeData()
$('.element').is(':animating');$('.element').is(':animated');$('.element').hasClass('animating');.attr() and .prop() for boolean attributes like “checked” or “disabled”?// Setting checked state
$('#checkbox').attr('checked', 'checked');
$('#checkbox').prop('checked', true);
.attr() manipulates HTML attributes (reflecting initial state), while .prop() manipulates DOM properties (current state)..attr() is deprecated and .prop() should always be used..attr() only works for string values, .prop() only works for boolean values.Source: .attr() vs .prop() vs .prop()
.end() method?Explanation:
The .end() method returns the previous set of matched elements in the chain, allowing you to back up one step in a chain of jQuery operations.
.andSelf() method do (deprecated in jQuery 1.8)?Explanation:
.andSelf() (now .addBack()) adds the previous set of elements on the stack to the current set. It was deprecated in jQuery 1.8 and replaced with .addBack().
$('[data]')$('[data-*]') or $('[data-attribute]') for specific attribute$('.data-*')$('data-*')Explanation:
To select elements with any data attribute, use $('[data-*]'). For a specific data attribute, use $('[data-attribute]') where attribute is the name.
.text() and .html()?.text() gets/sets text content only, .html() gets/sets HTML markup.text() is faster.html() is deprecatedExplanation:
.text() gets or sets the text content of elements (escaping HTML), while .html() gets or sets the HTML content (parsing HTML tags).
event.cancel()event.stopPropagation()event.preventBubbling()return false; (this stops both propagation and default)Explanation:
event.stopPropagation() prevents the event from bubbling up the DOM tree. return false stops both propagation and default action.
.serialize() method?Explanation:
.serialize() creates a URL-encoded text string from a set of form elements, useful for AJAX form submissions.
.serialize() and .serializeArray()?.serialize() returns a string, .serializeArray() returns an array of objects.serializeArray() is faster.serialize() is deprecatedExplanation:
.serialize() returns a URL-encoded string, while .serializeArray() returns an array of objects with name and value properties.
if ($('#element'))if ($('#element').length > 0)if ($('#element').exists())if ($('#element') !== null)Explanation:
jQuery always returns an object, even if no elements match. Check the .length property to see if elements were found.
.queue() method?Explanation:
.queue() shows or manipulates the queue of functions to be executed on the matched elements, typically used with animations.
.dequeue() method?Explanation:
.dequeue() executes the next function on the queue for the matched elements, advancing the queue.
$('.element').stop()$('.element').stop(true, true)$('.element').stopAll()$('.element').clearQueue()Explanation:
.stop(true, true) stops the animation, clears the queue, and jumps to the end. The first parameter clears the queue, the second jumps to the end.
.promise() method?Explanation:
.promise() returns a Promise object that resolves when all queued actions on a collection have finished.
.Deferred() object?Explanation:
$.Deferred() creates a chainable utility object for managing callback queues, providing a way to handle asynchronous operations.
.done() and .then() on a Deferred object?.done() is for success, .then() is for failure.then() returns a new promise, .done() returns the original deferred.done() is deprecatedExplanation:
.then() returns a new promise and allows chaining with transformation, while .done() returns the original deferred object.
$.createEvent('myEvent')$('#element').trigger('myEvent') or $.Event('myEvent')new Event('myEvent')$('#element').fire('myEvent')Explanation:
You can trigger custom events with .trigger('myEvent') or create event objects with $.Event('myEvent').
.triggerHandler()?Explanation:
.triggerHandler() triggers an event but doesn’t cause bubbling, doesn’t trigger default browser behavior, and only affects the first matched element.
$('#element').on('namespace.click')$('#element').on('click.namespace')$('#element').on('click', 'namespace')Explanation:
Event namespaces are added after the event name with a dot: 'click.namespace'. This allows selective unbinding of events.
$.proxy()?Explanation:
$.proxy() takes a function and returns a new one that will always have a particular context, similar to Function.prototype.bind().
.width() and .outerWidth()?.width() gets content width, .outerWidth() includes padding and optionally border/margin.outerWidth() is for outer elements.width() is deprecatedExplanation:
.width() returns the content width. .outerWidth() includes padding and border by default. .outerWidth(true) also includes margin.
.innerWidth()?Explanation:
.innerWidth() returns the width including padding but excluding border and margin.
$('#element').position()$('#element').offset()$('#element').documentPosition()$('#element').getPosition()Explanation:
.offset() gets the current coordinates of the element relative to the document. .position() gets coordinates relative to the offset parent.
.scrollTop()?Explanation:
.scrollTop() gets the current vertical position of the scroll bar. .scrollTop(value) sets it.
$('[attr~="value"]')$('[attr*="value"]')$('[attr|="value"]')$('[attr^="value"]')Explanation:
The *= selector matches elements with an attribute value containing the specified substring anywhere.
:has() selector used for?Explanation:
:has() selects elements which contain at least one element that matches the specified selector.
:contains() and :has()?:contains() matches text content, :has() matches descendant elements:contains() is case-sensitive:has() is deprecatedExplanation:
:contains() selects elements containing specific text. :has() selects elements containing specific descendant elements.
$('parent > :first')$('parent > element:first-of-type')$('parent > element:first-child')$('parent').first('element')Explanation:
:first-of-type selects the first element of its type among siblings. :first-child selects if it’s the first child regardless of type.
.is() method?Explanation:
.is() checks the current matched set of elements against a selector, element, or jQuery object and returns true if at least one matches.
$('.element:shown')$('.element:visible')$('.element:display')$('.element').visible()Explanation:
The :visible selector selects all elements that are visible (not display:none, visibility:hidden, or type=”hidden”).
$.contains()?Explanation:
$.contains(container, contained) checks whether a DOM element is a descendant of another DOM element.
$('#element').siblings()$('#element').siblings() (correct)$('#element').getSiblings()$('#element').brothers()Explanation:
.siblings() gets all siblings of each element in the matched set, optionally filtered by a selector.
.next() and .nextAll()?.next() gets the immediately following sibling, .nextAll() gets all following siblings.nextAll() is faster.next() is deprecatedExplanation:
.next() gets the immediately following sibling. .nextAll() gets all following siblings.
$('#start').to('#end')$('#start').nextUntil('#end')$('#start').until('#end')$('#start').range('#end')Explanation:
.nextUntil() gets all following siblings up to but not including the element matched by the selector.
.closest()?Explanation:
.closest() traverses up the DOM tree and returns the first ancestor element (including the element itself) that matches the selector.
.closest() and .parents()?.closest() returns first match and includes self, .parents() returns all ancestors.closest() is faster.parents() is deprecatedExplanation:
.closest() begins with the current element and travels up, returning the first match. .parents() begins with the parent and returns all ancestors.
$('.element').wrap('<div>')$('.element').wrap('<div>') (wraps each individually)$('.element').wrapEach('<div>')$('.element').wrapIndividual('<div>')Explanation:
.wrap() wraps each element in the matched set individually. .wrapAll() wraps all elements together as a group.
.wrapInner()?Explanation:
.wrapInner() wraps an HTML structure around the content (child elements) of each element in the matched set.
$('#element').removeParent()$('#element').unwrap()$('#element').parent().remove()$('#element').deparent()Explanation:
.unwrap() removes the parents of the matched elements from the DOM, leaving the matched elements in their place.
$.parseHTML()?Explanation:
$.parseHTML() parses a string into an array of DOM nodes, providing a safer alternative to using innerHTML.
$.parseJSON()?Explanation:
$.parseJSON() parses a JSON string and returns the resulting JavaScript value. It’s deprecated in favor of native JSON.parse().
$.ajax({
url: '/api/data',
headers: { 'X-Custom-Header': 'value' },
});
headers option in $.ajax()customHeaders option.setHeader() methodExplanation:
The headers option in $.ajax() allows you to set custom HTTP headers for the request.
$.ajaxSetup()?Explanation:
$.ajaxSetup() sets default values for future AJAX requests. However, it’s generally recommended to use specific options for each request instead.
var xhr = $.ajax({ url: '/api/data' });
xhr.abort();
.abort() on the jqXHR object.cancel() on the request.stop() on the requestExplanation:
The jqXHR object returned by $.ajax() has an .abort() method that can cancel the request.
context option in $.ajax()?Explanation:
The context option sets the value of this within all AJAX-related callbacks for that request.
$.ajax({
url: '/api/data',
method: 'POST',
contentType: 'application/json',
data: JSON.stringify({ key: 'value' }),
});
Explanation:
To send JSON data, set contentType to ‘application/json’ and use JSON.stringify() on the data object.
dataType and contentType in $.ajax()?dataType is expected response type, contentType is sent request typedataType is deprecatedcontentType is for headers onlyExplanation:
dataType specifies the type of data you expect from the server. contentType specifies the type of data you’re sending to the server.
$(document).ajaxError(function (event, jqXHR, settings, error) {
console.log('AJAX error:', error);
});
$(document).ajaxError()$.ajaxError()window.onerrorExplanation:
$(document).ajaxError() registers a handler to be called when AJAX requests complete with an error.
$.ajaxPrefilter()?Explanation:
$.ajaxPrefilter() allows you to modify or filter AJAX options before each request is sent and before they are processed by $.ajax().
$.fn.myPlugin = function () {
return this.each(function () {
// Plugin code
});
};
$.fn with your plugin function$.plugin with your function$.createPlugin()jQuery.prototypeExplanation:
jQuery plugins are created by extending $.fn (which is an alias for jQuery.prototype) with your plugin function.
this in a jQuery plugin?Explanation:
Returning this (the jQuery object) from a plugin enables method chaining, allowing users to call other jQuery methods after your plugin.
$.fn.myPlugin = function (options) {
var settings = $.extend(
{
color: 'red',
size: 10,
},
options,
);
// Use settings
};
$.extend() to merge default options with user optionsObject.assign()$.merge()Explanation:
$.extend() merges default options with user-provided options, allowing users to override defaults.
$.noConflict()?Explanation:
$.noConflict() releases jQuery’s control of the $ variable, allowing other libraries that use $ to work alongside jQuery.
$.noConflict()?var jq = $.noConflict();
jq('#element').hide();
jQuery instead of $window.$Explanation:
After $.noConflict(), you can use the returned alias or use jQuery instead of $ to access jQuery functionality.
$.fn.extend()?Explanation:
$.fn.extend() adds multiple methods to jQuery.fn, useful for creating plugins with multiple methods.
$.extend() and $.fn.extend()?$.extend() extends jQuery itself, $.fn.extend() extends jQuery.fn (prototype)$.fn.extend() is for functions$.extend() is deprecatedExplanation:
$.extend() adds methods to the jQuery object itself (utility functions). $.fn.extend() adds methods to jQuery.fn (instance methods).
$.version$.fn.jquery or jQuery.fn.jqueryjQuery.version$().versionExplanation:
The jQuery version is stored in $.fn.jquery (or jQuery.fn.jquery).
Explanation: jQuery Migrate plugin restores deprecated features removed from jQuery and provides console warnings to help identify deprecated code.
var copy = $.extend(true, {}, original);
$.extend(true, {}, original)$.clone(original)$.copy(original)$.deepCopy(original)Explanation:
$.extend(true, target, source) performs a deep copy when the first parameter is true.
$.grep()?Explanation:
$.grep() filters an array using a filter function, returning a new array with elements that pass the test.
$.map()?Explanation:
$.map() translates all items in an array or object to a new array of items using a translation function.
var result = $.merge(array1, array2);
$.merge(first, second)$.concat(first, second)$.join(first, second)first + secondExplanation:
$.merge() merges the contents of two arrays into the first array, modifying the first array and returning it.