Questions and Answers
- What's the difference between these two snippets?
- Only the second one will work; jQuery does not have a function called `.on`.
- The second snippet will not function.
- Nothing `.click(function)` is shorter way to write `.on('click', function)`.
- The first snippet will execute for every button on the page, the second will only apply to the first button.
- What does the following line of code do?
- Loads a paragraph tag from a remote server using AJAX
- Aliases jQuery to a variable p
- Selects all paragraphs on the page
- Creates a new paragraph tag and inserts it into the body tag
- Given the following HTML, how could we use one line to hide or show the button?
- `$('.btn-primary').toggle();`
- `$('.btn-primary').showHide();`
- `$('.btn-primary').not(':visible').show();`
- `$('.btn-primary').css({ display: 'block'});`
- Working with AJAX, we may run into situations where a piece of code should not be run until after multiple AJAX calls have completed successfully. Say we need to call two external services for JSON data (a list of students, and a list of classes). And only after retrieving those data will we perform some manipulations on a page. What is the preferred way for dealing with this scenario?
- A
- B
- C
- D
- Given the snippet of HTML below, what is the difference between the two lines that follow it?
- .get() retrieves a DOM element, and can't be chained, eq() retrieves a jQuery object, and can be chained.
- .get() retrieves a jQuery object, and can't be chained, eq() retrieves a DOM element, and can be chained.
- .get() retrieves a jQuery object, and is zero-indexed, eq() retrieves a DOM element, and is 1-indexed.
- .get() retrieves a DOM element, and is zero-indexed, eq() retrieves a jQuery object, and is 1-indexed.
- Suppose we want to have a ball created from an HTML element (id=ball) move down and to the right from its original location when clicked, and move back into its original place when finished. Given a starting point of this, which of these snippets would accomplish that goal?
- A
- B
- C
- D
- Given the following CSS and HTML codes below, how could you apply the success class to the feedback div?
- `$('.feedback').hasClass('.success');`
- `$.css('.feedback', '.success')`;
- `$('.feedback').addClass('success');`
- `$('.feedback').css('.success');`
- The following page snippet includes a couple of messages in a list, and a code snippet that retrieves a few hundred messages from an API endpoint using AJAX. How can you add these new items to the .message-area--list element in the most performant way?
- A
- B
- C
- D
- What is jQuery?
- jQuery is a bridge between Java and Javascript that makes native apps easier to write.
- jQuery is a plugin for JavaScript that makes database queries easier to write.
- jQuery is a collection of JavaScript functions that makes finding and manipulating elements on a page, AJAX, and other things easier.
- jQuery is a Chrome extension that allows users to create their own extensions with just a few lines of JavaScript.
- We want to create a new jQuery plugin called linkUpdater that can be chained onto other jQuery selector like a normal plugin. It should update all the links in the referenced collection so they open in new windows or tabs. Below is the first cut. What is one problem with this plugin?
- this needs to be wrapped, like `$(this)`, in order to be chained in a plugin.
- jQuery plugins can't be safely authored in strict mode.
- In order to be used by other code, plugins need to be added to the global namespace, not wrapped in a function expression.
- Our plugin should extend jQuery.fn, not jQuery itself.
- Generally speaking, when used on a web page, how should jQuery be installed, and why?
- Just before the closing body tag, because we want to avoid blocking other resources from loading, and we use the ready method to make sure our code fires after the DOM is ready
- Using the highest version number possible because only jQuery 3 and up are compatible with Internet Explorer 7
- In the head tag because we want jQuery available as soon as possible
- From a CDN because we want to be able to use jQuery online or offline
- Given the following HTML, how could we make this button disappear from the page using jQuery?
- `$('.btn-primary').hide();`
- `$('.btn-primary:visible').not();`
- `$('.btn-primary').visibility(false);`
- `$('.btn-primary').show(false);`
- What is the difference between `$('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.
- When writing jQuery plugins, we often provide default options that may be overridden by the end user. What jQuery function is most useful for this purpose?
- \$.extend
- \$.clone
- \$.fn.extend
- \$.merge
- There are times when you might want to programmatically trigger an event, instead of simply reacting to user input directly. Given this markup, Which choice will NOT cause a click event to the select box when the button is clicked?
- `$('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(); });`
- You have an absolutely positioned element inside a relatively positioned parent element, and you want to animate that element within its parent element. What jQuery function is most useful for finding the initial coordinates of the `.animate-me`?
- `$('.animate-me').offset();`
- `$('.animate-me').each();`
- `$('.animate-me').position();`
- `$('.animate-me').offsetParent();`
- You want to work with AJAX using a Promise-like interface instead of nested callback functions. What jQuery API should you use?
- `jQuery.sub`
- `jQuery.ajaxTransport`
- `jQuery.Deferred`
- `jQuery.proxy`
- What is tricky about jQuery's nth- filters (:nth-child, :nth-of-type, etc.) relative to other filters?
- Referring to lists of items, they are 1-indexed (like CSS), not 0-indexed (like JavaScript).
- They don't return the jQuery object, and cannot be chained.
- They can return the wrong items if the DOM was recently manipulated.
- They are not part of CSS, so they don't get the performance benefits of passing through the `document.querySelectorAll`.
- jQuery's AJAX functions return objects that implement the Promise API. As a result, you can chain promises and avoid nested callbacks. What does that look like?
- A
- B
- C
- D
- You want to have a ball that is created from an HTML element (id=ball) move down and to the right of its original location when clicked, and move back to its original place when finished. What snippet, added to the code below, would do this?
- A
- B
- C
- D
- The way `.wrap()` works is sometimes misunderstood. Given the DOM and jQuery snippets below, what does the modified DOM snippet look like?
- A
- B
- C
- D
- How can you select the following blockquote AND the list in a single call to jQuery() without chaining?
- `$('.quotes + .menu-first')`
- `$('.quotes .menu-first')`
- `$('.quotes, .menu-first')`
- `$('.quotes' + '.menu-first')`
- Effects like show, hide, fadIn, and fadeOut can be called with no arguments, but can also take arguments for how long they should last. Which is NOT a duration argument supported by these functions?
- "fast"
- "extreme"
- 2000
- "slow"
- Though jQuery offers visual effects, it is considered a best practice to use CSS to set up different states triggered by classes, where it makes sense. What's the easiest way to enable and disable a class bounce on an element with the ID dialog?
- `$('#dialog').classToggle('bounce')`
- `$('#dialog.bounce').removeClass().addClass()`
- `$('#dialog').addOrRemoveClass('bounce')`
- `$('#dialog').toggleClass('bounce')`
- What is the main difference between selectors and filters?
- Selectors are used to refine the content that filters have been applied to.
- Selectors are used to find and select content in a page. Filters are used to refine the results of selectors.
- Filters are used to remove content from the page. Selectors are used to add content to the page
- There is no real difference. They are both used to build up lists of page content.
- You want to create a custom right-click menu. How might you start the code?
- `$('#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') });`
- What is the correct way to check how many paragraphs exist on a page using jQuery?
- `$('p').count()`
- `$('p').length`
- `$('*').find('p')`
- `$('p').length()`
- As with many areas of JavaScript, keeping track of the meaning of **this** is important and sometimes tricky. What does **this** mean at each of the two points in this custom plugin snippet?
- At Point 1, `this` means a jQuery object. At Point 2, it means a DOM element.
- In this case, they mean the same thing: a jQuery object.
- In this case, they mean the same thing: a DOM element.
- At Point 1, `this` means a DOM element. At Point 2, it means a jQuery object.
- How can you make the first list item bold and the next item oblique, in a single statement chain?
- A
- B
- C
- D
- Which CSS selectors can you NOT use in jQuery?
- You cannot use multiple class selectors such as `.class1.class2`.
- You cannot use pseudo-classes such as `:not` or `:last-of-type`.
- You cannot use IDs and classes together, such as `#element.class`.
- None. All CSS selectors are compatible in jQuery.
- Starting with some DOM elements in the nested structure below, you assign listeners for the same event to a child element and one of the parents using the JavaScript that follows. You want to ensure that when `.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?
- `event.capture();`
- `event.stopPropagation();`
- `event.preventDefault();`
- `event.stop();`
- Using event delegation, you can listen for events on a lot of different items without having to attach separate listeners to each one. But there are times when you may want to check the type of item receiving the event before doing anything, such as checking if an image was clicked versus a text field. Given the starter code below, which choice shows what jQuery provides to help with that process?
- `$($target.get(0) + ':image')`
- `$('img').is($target)`
- `$target.filter('img')`
- `$target.is('img')`
- There are many ways to create elements that can be added to the page. Which answer is NOT one of those ways, assuming you have the following on the page?
- A
- B
- C
- D
- The `.addClass()` and `.removeClass()` methods can accept functions as arguments. What does this function do?
- It adds the first class found on the body element to the #menu element.
- It adds all classes found on the #menu element to the body tag.
- It replaces any classes on the #menu element with all classes from the body tag.
- It adds all classes found on the body element to the #menu element.
- You're working on a site that uses an old version of jQuery, and you want to update to a newer version. What's the most efficient way to do so?
- Install the newer version of jQuery, go through each script one by one, and fix what looks broken.
- Read the change notes for the newer version of jQuery, fix all scripts, install the newer version, and fix anything that remains broken.
- Install the newer version of jQuery as well as its Migrate plugin, fix all warnings, and uninstall the Migrate plugin.
- Install the newer version of jQuery at the same time, and use `jQuery.noConflict()` on pages that need the older version.
- Let's say you have a page with just one link on it. How can you change the anchor tag so it links to example.com?
- `$('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')`
- What does `$()` mean in jQuery?
- It is an alias to the main core method of jQuery itself?the same as writing jQuery().
- It is a utility function that selects the first element from the document.
- It is a shorter way to write `document.getElementById()`.
- It is a utility function that selects the last element from the document.
- Along with DOM traversal and manipulation, jQuery offers several general-purpose helper functions that fill in some JavaScript gaps, especially before ES2015. Which is NOT a jQuery utility function?
- `jQuery.each`, a general purpose iterator for looping over arrays or objects
- `jQuery.isNumeric`, which can check whether its argument is, or looks like, a number
- `jQuery.extend`, which can merge objects and make complete deep copies of objects
- `jQuery.isMobile`, which can tell whether the user is using a mobile browser
- Given this set of checkboxes, how can you select the ones that have the phrase "sun" as part of the value?
- `$('checkbox').val(/sun/);`
- `$('input[value*="sun"]');`
- `$('input[value|="sun"]');`
- `$('input:checkbox').attr('value', '*sun*');`
- How can you get an AJAX request to go through without triggering any of jQuery's AJAX events?
- Set the type option to "none".
- Set the processData option to false.
- Set a success callback that returns false.
- Set the option "global" to false.
- How do you change the current value of a text field with the class `.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');`
- How would you fire a callback when any AJAX request on a page has completed?
- `$('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'); });`
- Given this set of checkboxes, how can you select the one with the value "blimp"?
- `$('input[value="blimp"]');`
- `$('input[value!="blimp"]');`
- `$('checkbox').val('blimp');`
- `$('input:checkbox').attr('value', 'blimp');`
- Given this snippet of HTML and jQuery code, what does the jQuery do?
- It makes all the menu items bold.
- It throws an exception on line 3.
- It makes the first set of menu items, not the second, bold.
- It makes the second set of menu items, not the first, bold.
- You want to take a block of type and animate it to a larger size with jQuery. The following HTML and JavaScript behaves strangely. What is the issue?
- jQuery does not support ems and will make the type 1 pixel larger instead of 1 em larger.
- jQuery cannot override CSS in a style attribute, so the font size will not change.
- The font size was set with a shorthand property, so jQuery will not animate the font size at all.
- The font size was set with a shorthand property, so jQuery will start the animation from 0 instead of from 1 em.
- When using the `clone()` function to duplicate an element, what is one of the main concerns your code needs to watch out for?
- The `clone()` function may ignore data attributes on the original elements.
- The `clone()` function may result in elements with duplicate ID attributes.
- The `clone()` function may remove CSS classes from the cloned elements.
- The `clone()` function may not respect the attribute order of the original elements.
- When incorporating a plugin into a project, what are the important steps for basic installation and usage?
- The jQuery script tag must come first, followed by the plugin, followed by your custom scripts, all preferably at or near the bottom of the page.
- Your custom scripts must appear first in the document ``, followed by jQuery, followed by the plugin.
- The jQuery script tag and the plugin script tag must appear in the document ``, and your custom scripts can follow anywhere on the page.
- The jQuery script tag must appear in the document ``, but the plugin and your custom scripts can appear anywhere else in any order.
- These two script tags show different ways of using jQuery's `ready()` method. What is true about both approaches?
- The code inside them can manipulate the DOM safely, knowing the browser has loaded it fully.
- The code inside them can manipulate images on the page safely, knowing they have fully downloaded to the browser.
- The code inside them will be run exactly once per user session.
- The code inside them is not aware of the DOM.
- Which describes how jQuery makes working with the DOM faster?
- jQuery optimizes the DOM in a background thread, making updates faster.
- jQuery avoids using the DOM at all.
- jQuery uses a virtual DOM that batches updates, making inserts and deletes faster.
- jQuery code to perform DOM manipulation is shorter and easier to write, but does not make DOM operations faster.
- There are some issues with this snippet of jQuery. First, it is manipulating CSS directly, rather than manipulating classes and leaving the CSS in stylesheets. What else in this code is best to avoid?
- The `.css()` method accepts only an object, not two separate arguments. This will trigger an exception that should be caught.
- The `$('.item')` selection is being made several times. This should be cached in a variable for (however slightly) better performance and easier maintainability.
- The call to `.parents()` is in an inefficient place.
- All the calls to `$('.item')` should be chained together as a single executable line for better performance.
- Which choice is an example of statement chaining?
- `var $p = $('p'); console.log($p.length);`
- `$('p').find('a').children('li');`
- `$('p > a > li');`
- `$('p'); $('a'); $('li');`
- How can you ensure that some code executes only when a class `active` appears on an element?
- `$('.element').attr('class', 'active')`
- `$('.element').with('.active')`
- `$('.element').hasClass('active')`
- `$('.active').then()`
- jQuery has a main function for handling AJAX, and several shorthand function including `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?
- `$('#load-me').get('source.html#one');`
- `$('#load-me').get('source.html #one');`
- `$('#load-me').load('source.html #one');`
- `$('#load-me').load('source.html', '#one');`
- Given this HTML list and subsequent two lines of jQuery, what is the difference in the behavior of `.closest()` and `.parents()`?
- `.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`.
- What does this line of code do?
- selects the first list item inside all unordered lists on the page
- selects the first list item inside the first unordered list on the page
- selects the first element inside any list items on the page
- creates a predefined CSS selector that can be reused later
- Below is a list of items that you want to be clickable and an event handler function. How can you assign the event handler to every item in the list in a way that is most performant, and also that ensures that the handler is called even if more items are added to the list programmatically?
- `$('.clickable-list').click(listResponder);`
- `$('.clickable-list').on('click', 'li', listResponder);`
- `$('.clickable-list').on('click, append', listResponder);`
- `$('.clickable-list').each(function() { $(this).click(listResponder); });`
- What is the difference between $('p').find('a') and $('p').children('a')?
- `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 element`
- `children() traverses only one level down, whereas find() selects anything inside the original element`
- Consider the following markup, used to lay out three balls on the page, all hidden. How can you select the green ball, make it faded in over the course of three seconds, and log a console message when the animation has finished?
- A
- B
- C
- D
- Why might you use custom events instead of shared helper functions? For example
- `Custom events are at least an order of magnitude faster than helper functions`
- `Custom events can be listened for and acted upon across one or more scripts without needing to keep helper functions in scope`
- `Handler functions for custom events are less likely to be mangled by minification and obfuscation build tools`
- `It is easier to write documentation for custom events than it is for helper functions`
- In the HTML and JavaScript below, the animations will all fire at once. How can you make them fire in sequence instead?
- A
- B
- C
- D
- Given this checkbox, how can you determine whether a user has selected or cleared the checkbox?
- by checking the value of `$('#same-address').val()`
- by checking the value of `$('#same-address').prop('checked')`
- by checking the value of `$('#same-address').attr('checked')`
- by checking the value of `$('#same-address').checked`
- In some projects, jQuery is not included as a file with an obvious version number (if it has been run through a minifier or other code bundler, for example). How can you detect programmatically what version of jQuery is active?
- `jQuery.version()`
- `jQuery.jquery`
- `jQuery.prototype.version`
- `jQuery.fn.jquery`
- Given this snippet of HTML, how can you get the value of the text field using jQuery?
- `$('input[type=text]').val()`
- `$('.form-control').val()`
- `all of these answers`
- `$('#firstName').val()`
- Which property of the jQuery event object references the DOM object that dispatched an event?
- target
- self
- source
- object
- You want to write a plugin that creates a new traversal function?such as parent() and children()?and behaves like the ones jQuery includes out of the box. It needs to correctly modify the list of selections jQuery tracks internally, build up a list of additional items, and return the merged collection. What do you need to return on the last line of the function in order for this plugin to work correctly?
- `return this.append(additionalItems);`
- `return additionalItems.appendTo(this);`
- `return this.pushStack(additionalItems);`
- `return this.add(additionalItems);`
- Given this snippet of HTML and jQuery code, what will the result look like?
- A
- B
- C
- D
- jQuery can create event handlers that execute exactly once. How is this done?
- `$('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'); });`
- You want to implement the behavior of an effect like `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.
- Effects created with `animate()` must be run over at least 100 milliseconds, where `slideDown()` can run as quickly as 50ms.
- If you JavaScript project involves a lot of DOM manipulation, but no AJAX or animation, which version of jQuery should you use?
- jQuery 3 compressed
- jQuery 3 slim
- jQuery 2
- None of these - jQuery requires AJAX
- The `.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?
- A
- B
- C
- D
- You want to take an element and any event handlers that go with it out of the DOM to do some work?without the changes affecting the rest of the page?and then move it somewhere else in the DOM, like right after the opening tag. What should go on the first line of this code snippet?
- `var $example = $('#example').remove();`
- `var $example = $('#example').clone();`
- `var $example = $('#example').detach();`
- `var $example = $('#example').addBack().empty();`
- What is a particular performance concern when dealing with event handlers, and how can you cope with it?
- Finding which element an event occurred on is expensive. Assign most events to document.body and use .is() to act on the element of interest.
- Some events, such as mousemove and scroll, happen a lot on a typical page. Debounce or throttle their handlers to make sure the handlers are not called more than you actually need.
- Listening for an event that does not exist can create serious memory leaks. Be careful to spell event names correctly to avoid consuming too much memory.
- DOM elements with an ID wil fire events more efficiently than with classes. Always use IDs instead of classes where possible.