jQuery 1 Flashcards
Under what circumstances is it not necessary to use document.ready()?
If you place code just before closing body tag, you don’t need it — the result will be the same.
You want to find all cases where class = “special” within a div with id = “container”; what are two ways to do this?
- Use context parameter: $(“.special”, “#container”);
2. Use find(): $(“#container”).find(“.special”);
What can the filter() method do that find() or just plain old $(“.someClass”) can’t do?
- It can find things that aren’t in the DOM (e.g. in a documentFragment).
- It can take a function which takes one argument, index.
What does end() do?
It reverts the selection to its prior state. $(‘p’).find(‘.someClass”)..perform some actions on someClass set….end()…perform some actions on set of p tags.
Find an element in a given set by index (integer)
Use the eq(i) function: $(“li”).eq(1);
Alt: $(“li:eq(1)); // NOT AS FAST
Name 10 DOM manipulation methods
append(), prepend(), prependTo(), after(), before(), insertAfter(), insertBefore(), wrap(), wrapAll(), wrapInner()
What are two ways to select the direct descendants (children) of ul that are li elements?
$(“ul”).children(“li”) or $(“ul > li”);
What are the three kinds of selector filters?
Basic, Child, and Content Filter. Basic: things like :eq, :first, :lt, :not Child: :first-child, :nth-of-type, etc Content: :contains(), :has(), :empty. Note: always use with colon.
How could you find all paragraphs that included the text “Hello”?
What if it could be “hello” or “hi” or “hiya”?
- $(“p:contains(‘Hello’));
- $(“p”).filter(function( ) { return pattern.text($(this).text());
}
Select all input elements except those that are hidden:
$(‘:input:not(:hidden)’);
Select both all input elements and all textarea elements in one call:
$(‘textarea, :input’);
Select all images with a common extension of jpg:
$(“img”).filter(function(index){
return /.jpg/.test(this.src);
} // this points to the element not the jquery object
Match all div elements with ids like id=”card-1”, id=”card-2”, id=”card-3” etc
$(“div[ id^=’card-‘ ]”);
What does [attr$=val] do?
It matches elements that have a particular attribute with a name ending in val. E.g. $(“[id$=’card’]”) will match div id=”big-card”, id=”wide-card”, and id=”small-card”
How would you select every element that had a css background image?
$(“*”).filter(function(i){
return !! $(this).css(“backgroundImage”);
}; // !! not necessary but helps clarify
How can you extend jQuery’s selector expressions, say, if you wanted to create a custom filter for finding only inline elements.
Use the jQuery.expr[":"] object: $.expr[":"].inline = function(elem, index, array){ // must return true or false return $(elem).css("display") === "inline"; }
How is the $(selector).each() method different from the javascript array.prototype.forEach() method?
jQuery each() takes a function that takes only one argument, the index. You can stop the loop by returning false at any time. Note that there is a separate utility function called each() which is different. JS forEach() takes a function with 3 params: item, index, array.
How can you convert a jQuery object to a raw DOM object? (e.g. instead of the $(“p”) list, you want the list of DOM nodes).
Use array notation, $(“p”)[ 0 ] will get the first node with nodeName of “paragraph”.
Or use get( ) with optional index (which can be negative). No index will return an array of nodes.
What does $.grep() do?
It’s a filter method for arrays. Like the native filter method but it takes an array and then a function. Ex: newArray = $.grep(oldArray, function(item, index)) { //return true or false }
What is the difference between $.merge() and array.concat()?
merge takes two arrays as arguments and returns the second one concatenated to the first (it changes the first array).
concat() creates a third array that it returns.
How do you get the value of an input field?
$(“someInput”).val();
If $input is an input field, how do you remove whitespace from its contents?
Use the trim utility:
$.trim( $input.val( ));
What is an expando and why can it cause problems?
It’s a property added to an object or DOM node at runtime. It can cause garbage collection problems.
What is the jQuery.data() method?
It allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks.
How do you set data on a DOM element using $.data()?
Pass three arguments: the element to assoc. with the data; a string key to name the piece of data; and an object that can contain n values. Ex: jQuery.data( div, “food”, { lunch: “soup”, dinner: “pizza” });
Assume we have a jQuery object, $myDiv, which has data associated with it. If the data has a key of “food”, how can you access the property called “dinner”?
$.data( $myDiv, “food” ).dinner );
How do you alias jQuery with $?
Use a self-invoking anonymous function, in which you pass jQuery:
(function($){ some jquery code…})( jQuery )
Which is faster and why?
$(“#id li.someclass”) or $(“#id”).find(“li.someclass”);
The latter, because sizzle isn’t necessary — near the top of jQuery, it identifies if the selector is an id, and if it is it uses getElementById(); With the former, it has to do a bunch of stuff before it even determines that it can use the id.
What does it mean when you add a function to jQuery.fn?
It’s the same as adding it to jQuery.prototype.
How do you use jQuery bind() method?
It’s deprecated, so use on();
How do you use jQuery on() method?
Pass it an event type and a function:
on (“submit”, function(event){ // });
Note that there are a bunch of shorthand ways to handle certain types of events. You can also pass data to the handler.
How do you reduce name lookups in a loop?
If the loop is inside of one or more nested functions, and that loop handles variables, every iterations it will need to look up each variable starting with local and working up to global. Math.abs will look locally, then in outer function and so on. Just cache the references, as in: var abs = Math.abs.
what’s a shorthand way to get the current time in milliseconds?
var t1 = +new Date;
What does html() method do?
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element. It uses native innerHTML but cleans is up.
How can you prevent animations from getting out of control when using hover effects?
Animations get put in a queue, so it’s smart to stop all existing animations in the queue before starting a new one. Use stop( true ) with true indicating that all animations should be cleared from the queue. y
How can you pass data to an event handler? And why would you want to?
The on() method takes an optional data parameter: $("someSelector").on( "click", { key: value }, handler }); // You might want to use the same handler for a variety of events or selectors. The data object enables you to do specific things for each of them.
What is the best way to delegate events in jQuery?
Use the on() method with optional descendent selectors. This will attach only one event listener which will delegate to those descendents:
$(“div”).on( “click”, “.class1, .class2”, handler);
For best performance, attach delegated events where in relation to the target elements?
Attaching many delegated event handlers near the top of the document tree can degrade performance. Attach a document location as close as possible to the target elements.
How could you attach an event handler that fired only once (without manually removing the handler)?
Use the one() method:
$( “p” ).one( “click”, function() {
alert( “that’s it!”);
});
What will this do?
$(“#someDiv”).off( );
It will remove all event listeners that are attached to the #someDiv element.
How could you be specific in removing listeners from an element?
Pass the selectors and handler used in on(). Selectors must be the same and in same order.
$(“#id”).off( “click”, “.childOfID”, handler);