jQuery 1 Flashcards

1
Q

Under what circumstances is it not necessary to use document.ready()?

A

If you place code just before closing body tag, you don’t need it — the result will be the same.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

You want to find all cases where class = “special” within a div with id = “container”; what are two ways to do this?

A
  1. Use context parameter: $(“.special”, “#container”);

2. Use find(): $(“#container”).find(“.special”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What can the filter() method do that find() or just plain old $(“.someClass”) can’t do?

A
  1. It can find things that aren’t in the DOM (e.g. in a documentFragment).
  2. It can take a function which takes one argument, index.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What does end() do?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Find an element in a given set by index (integer)

A

Use the eq(i) function: $(“li”).eq(1);

Alt: $(“li:eq(1)); // NOT AS FAST

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Name 10 DOM manipulation methods

A

append(), prepend(), prependTo(), after(), before(), insertAfter(), insertBefore(), wrap(), wrapAll(), wrapInner()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are two ways to select the direct descendants (children) of ul that are li elements?

A

$(“ul”).children(“li”) or $(“ul > li”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the three kinds of selector filters?

A
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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How could you find all paragraphs that included the text “Hello”?
What if it could be “hello” or “hi” or “hiya”?

A
  1. $(“p:contains(‘Hello’));
  2. $(“p”).filter(function( ) { return pattern.text($(this).text());
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Select all input elements except those that are hidden:

A

$(‘:input:not(:hidden)’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Select both all input elements and all textarea elements in one call:

A

$(‘textarea, :input’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Select all images with a common extension of jpg:

A

$(“img”).filter(function(index){
return /.jpg/.test(this.src);
} // this points to the element not the jquery object

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Match all div elements with ids like id=”card-1”, id=”card-2”, id=”card-3” etc

A

$(“div[ id^=’card-‘ ]”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does [attr$=val] do?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How would you select every element that had a css background image?

A

$(“*”).filter(function(i){
return !! $(this).css(“backgroundImage”);
}; // !! not necessary but helps clarify

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How can you extend jQuery’s selector expressions, say, if you wanted to create a custom filter for finding only inline elements.

A
Use the jQuery.expr[":"] object:
$.expr[":"].inline = function(elem, index, array){
    // must return true or false
    return $(elem).css("display") === "inline";
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How is the $(selector).each() method different from the javascript array.prototype.forEach() method?

A
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.
18
Q

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).

A

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.

19
Q

What does $.grep() do?

A

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 }

20
Q

What is the difference between $.merge() and array.concat()?

A

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.

21
Q

How do you get the value of an input field?

A

$(“someInput”).val();

22
Q

If $input is an input field, how do you remove whitespace from its contents?

A

Use the trim utility:

$.trim( $input.val( ));

23
Q

What is an expando and why can it cause problems?

A

It’s a property added to an object or DOM node at runtime. It can cause garbage collection problems.

24
Q

What is the jQuery.data() method?

A

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.

25
Q

How do you set data on a DOM element using $.data()?

A

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” });

26
Q

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”?

A

$.data( $myDiv, “food” ).dinner );

27
Q

How do you alias jQuery with $?

A

Use a self-invoking anonymous function, in which you pass jQuery:
(function($){ some jquery code…})( jQuery )

28
Q

Which is faster and why?

$(“#id li.someclass”) or $(“#id”).find(“li.someclass”);

A

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.

29
Q

What does it mean when you add a function to jQuery.fn?

A

It’s the same as adding it to jQuery.prototype.

30
Q

How do you use jQuery bind() method?

A

It’s deprecated, so use on();

31
Q

How do you use jQuery on() method?

A

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.

32
Q

How do you reduce name lookups in a loop?

A

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.

33
Q

what’s a shorthand way to get the current time in milliseconds?

A

var t1 = +new Date;

34
Q

What does html() method do?

A

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.

35
Q

How can you prevent animations from getting out of control when using hover effects?

A

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

36
Q

How can you pass data to an event handler? And why would you want to?

A
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.
37
Q

What is the best way to delegate events in jQuery?

A

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);

38
Q

For best performance, attach delegated events where in relation to the target elements?

A

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.

39
Q

How could you attach an event handler that fired only once (without manually removing the handler)?

A

Use the one() method:
$( “p” ).one( “click”, function() {
alert( “that’s it!”);
});

40
Q

What will this do?

$(“#someDiv”).off( );

A

It will remove all event listeners that are attached to the #someDiv element.

41
Q

How could you be specific in removing listeners from an element?

A

Pass the selectors and handler used in on(). Selectors must be the same and in same order.
$(“#id”).off( “click”, “.childOfID”, handler);