JQuery Flashcards

1
Q

What function can be used to delay execution of a script until the page is fully loaded?

A

$(document).ready();

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

When adding a new element to a page dynamically, you find events are not working for these new items. What could the issue be?

A

If the event was setup using $(‘id’).click, creating a new element doesn’t seem to bind the event. Use the $(‘body’).on(‘click’ ….) function call instead.

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

Instead of using $.get, what is another method?

A
$.ajax({
   type: 'GET',
   url: url,
   data: data,
   dataType: 'json'
});
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What field, in the $.ajax call configures the callback?

A

success

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

Given an element with a data attribute as such ‘data-set=”4 ,1”’ - how would you select the element if it had the number 4 as one it’s values?

A

$(“[data-set~=’4’]”)

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

How would you load content into a div from a separate HTML file?

A

$(‘#divid’).load(‘content/mycoolcontent.html’);

Do this once the page has loaded, and the html content will be loaded into the page at the location specified by the #id.

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

What is the issue with using window.outerWidth to determine screen size?

A

It doesn’t take into account scroll bars and other such intrusions. The actual content width is usually a bit smaller - and the problem is that media queries use the content width, whereas JavaScript gives you the outerwidth.

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

How might you write a function that detects screen size change?

A
function checkBrowserSize() {
    windowWidth = window.outerWidth;
    var contentWidth = $('body').width(); 
    var sizeDiff = windowWidth - contentWidth;
    actualSize = windowWidth - sizeDiff;
    if (actualSize > 800) {
        newWindowSize = 'large';
    } else if (actualSize  500) {
        newWindowSize = 'medium';
    } else if (actualSize
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

When using jQuery to animate, you may find that between media queries, the position of elements are not entirely what was expected. Why might this be?

A

The jQuery animate function adds a ‘style’ attribute to the targeted elements. This could be overriding the css. So you need to remove that style.

$(this).removeAttr(‘style’); (where ‘this’ is targetting the element with the attribute)

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

window.outerWidth does not work in IE 7 and 8. How would you go about determining the size of the window?

A

NOTE: isIE is a variable set by checking support.leadingWhitespace.

    if (isIE) {
        windowWidth = $('body').width() + 33;
    } else {
        windowWidth = window.outerWidth;
    }

The windowWidth will now have a value (we are using jQuery) - although the + 33 is an arbitrary value, we don’t actually know if there is a scroll bar or not.

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

What is the difference between the ready and the onload event?

A

onload fires after all images and code has loaded (so it’s blocking). The ready event fires once the DOM has loaded - which means it will fire a lot earlier.

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

What is the difference between “.html” and “.text” methods?

A

.html inserts html, whereas .text will insert escaped text, meaning you will see any tags etc in the output.

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

What JQuery method can you use to stop events from listening?

A

.off

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

When you get an array back from a JQuery selector, is the array an array of DOM elements?

A

No - it’s an array of objects that wrap each of the DOM elements.

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

What is the difference between a selector and a filter?

A

Selectors find the elements, whereas filters select from a group of elements (chosen by a selector) based on a more granular requirement. For instance.

$(“p”) - selects all of the p elements.
Adding the filter :first
$(“p:first”) - selects only the first p element

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

How would you select paragraph elements that have an index greater than 1?

A

$(“p:gt(1)”)

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

How could you use a selector to select all of the p elements bar the second one?

A

$(“p:not(p:eq(2))”)

So we are saying here, grab all elements, but not the one equal to 2.

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

Can you chain attribute selectors with JQuery?

A

Yes

$(“p[id^=para][lang*=eng-]”)

We are looking for “p” tags that contain an attribute (id) that starts with the word “para” and a lang attribute that contains the word “eng-“.

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

What does the :contains filter do?

A

It looks at the actual contents of the selector, to see if the specified content is in the tag.. i.e.

$(“p:contains(‘superman’)”)

Would select any p elements that contain the words “superman”.

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

What does the :parent filter do?

A

Selects all P tags that are parents, i.e. they contain some other tag.

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

What does the :has filter do?

A

It allows you to search for an element that has another element with some specific condition. i.e.

$(“div:has(p[class=a])”)

Give me all the divs that contain a paragraph element that has a class with a in it

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

What would the following selector select?

$(“div p:first-child”)

A

The first p, that is a child, and within a div.

NOTE: It’s not necessarily the first p that is a child of the div, but a p that is a first-child somewhere inside the div.

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

How would you select the last p in a div, without using last-child?

A

$(“div p:last-of-type”)

NOTE: if there are other divs/containers within the outer div, then the p:last-of-type will apply to those containers too. It’s last-of-type at that level.

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

What is unusual about using nth-child filter?

A

It’s not 0 based, it starts at 1.

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

How does the nth-child expression work?

A

You can pass it a value n - to get you every nth element.

i.e. p:nth-child(2n) will give you every second one.

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

What function will return all the parents of an element, up until a specified parent element?

A

parentsUntil($(“body”));

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

Write a coupleo f lines code that get the element with the “para1” class, and apply a 3px red solid border to it’s parent.

A
var element = $(".para1");
element.parent.css("border", "3px solid red");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

How does the find function work?

A

You can use it to search through the DOM tree to find an element that is starting at a certain element. i.e.

$(“#example”).find(“.foobar”).css(“border”, “2px solid red”);

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

How does the “each” function work?

A

It allows you to specify a callback function that will be run for each element found based on a selector. i.e.

var leftmargin = 0;
var border = 3;
$(“#example p”).each(function(index, element) {
$(element).css(“border”, border+”px solid red”)
.css(“margin-left”, leftmargin+”px”);
border += 2;
leftmargin += 10;
});

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

The second argument passed to the callback in the each function is a jquery object, or a dom element?

A

A dom element, so you have to pass it to JQuery to turn it into a jquery object.

$(element)

NOTE: no quotes, because it’s a var.

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

There are two ways to create a jQuery object containing a HTML DOM object, what are they?

A

Directly - but inserting the element into the page using the html tag.

$(“#myElement”).html(“Stuff”);

And by passing a full string to the jQuery object, and assigning it to a variable.

var myjQueryObject = $("Stuff");
$("#myElement").html(myjQueryObject);

// NOTE: The contents of both examples (“stuff”) should be wrapped in HTML tags, but because of brainscapes stupid way of handling HTML, it’s not easy to do reliably.

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

What is the usage difference between the append and appendTo functions?

A

$(“#id”).append(“Some text”);

$(“Some Text”).appendTo(“#id);

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

The functions, append, prepend, appendTo and prependTo insert text/html inside the selectors element. How would you insert text/html BEFORE the element?

A

Use the functions
before
after

$(“p”).before(“This is text that goes before”);

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

What would the following code do?

$(“#example p:last”).appendTo(“#example p:first”);

A

It would actually take the last paragraph, and append it to the first paragraph. So:

paragraph 1
paragraph 2
paragraph 3

would end up looking like

paragraph1
paragraph3
paragraph2

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

append has appendTo, what is the equivalent for after?

A

insertAfter
insertBefore

(i.e. you specify the content first, then the selector)
$(“stuff”).insertAfter(“#myElement”);

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

What does the wrap function do?

A

It allows you to wrap content around existing content. For instance:

$(“#example p”).wrap(“div style=’red’”);

NOTE: That you only have to provide a closed tag, you don’t need to have the open and closed tag - jquery will work it out.

NOTE: I’ve left out the greater / less than signs because brainscape can’t deal with them (even as html characters).

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

What is the difference between wrap and wrapAll?

A

When jQuery returns a set of jQuery objects based on a selector, wrap will wrap each one with the provided html tag.

However, wrapAll will simply wrap ALL of the jQuery objects with a single element.

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

What does the .empty() function do?

A

Given a selector, it will remove all of the child elements. I.e. it empties containers.

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

What is the difference between remove and detach functions?

A

Remove will remove all of the specified elements (via the selector) and also all of their data and event handlers.

However, detach will remove the specified elements (via the selector), but LEAVE all of the data and event handlers untouched. The contents of the tags are gone - but if you put those elements BACK into the page later, then any data or event handlers that you have added to those elements will still work.

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

What is the purpose of the replaceAll / replaceWith functions?

A

They simply find an element in the document, and replace it with the specified text.

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

What is the difference between replaceAll and replaceWith

A

Basically the order in which you provide the arguments. They both replace all the matches.

$(“A string or HTML”).replaceAll(“p”);
$(“p”).replaceWith(“A string or HTML”);

42
Q

What is one nice feature of replaceWith regarding how you determine selectors?

A

You can pass it a callback function, which can determine elements on the fly. NOTE: The callback will be called for each jQuery object in the set - so the callback should deal with each one individually, and determine if it matches. Then it should return the element that it will replaceWith.

43
Q

When you have a callback function (say for the replaceWith function), and you see the following code, what is it doing?

$(this)

A

Typically, the callback function will be called within a given context. For example, that may be the context of each element in a set of jQuery objects.

If that is the case, the “this” variable in the calleback will refer to the DOM element (not the jQuery object itself). So to operate on the DOM element with jQuery, you must revert it to a jQuery object, by passing it to the jQuery object.

$(this).text();

44
Q

What does the following do?

$(this).text().indexOf(1)

A

It finds the index (string array) of the value “1” in the given jQuery object. So if it was a DOM element with a string of “I love 1’s”, it would return a value of 7.

45
Q

What function is used to set an attribute?

A

$(“img”).attr(“title”, “Great images”);

46
Q

How can you use the attr function to retrieve the value of an attribute?

A

If you don’t pass the second argument, it will return the value.

$(“img”).attr(“title”);

47
Q

Setting the target on an anchor link to _blank does what?

A

It ensures it opens in a new window

$(“a”).attr(“target”, “_blank”);

48
Q

The text that appears over images when you hover is derived from…

A

The title attribute

49
Q

How do you remove an attribute from an element?

A

$(“a”).removeAttr(“href”);

50
Q

How would you change multiple attributes at the same time?

A

You can pass a json object to the attr function

$(“img”).attr({ src: “src/image.jpg”, title: “fun spring stuff” });

51
Q

What are the different ways to call .css?

A

.css(propertyName) - returns value
.css(propertyName, value) - sets value of property
.css(propertyName, func) - sets value of prop based on return value of func
.css(properties) - set multiple values at once

52
Q

How can you determine if an element has a specific class?

A

.hasClass(classname)

53
Q

How can you turn off/on a class?

A

.toggleClass(classname)

54
Q

How can you remove a css class?

A

.removeClass(classname(s))

55
Q

How do you add a class to an element?

A

.addClass(classname)

56
Q

What does the following do?

css(“font-size”, “+=1pt”);

A

It increases the font size (the current font size, whatever that is) by 1pt

57
Q

How would you send a Javascript Object to the .css function?

A
$("#example").css({
   "font-weight": "bold",
   "font-size": "2pt",
   "color": "aubergine"
});
58
Q

When using jQuery to receive widths/heights etc, what is one of the things you must be mindful of?

A

You will receive fractional values. So you must be careful not to assume that they are always integer values.

59
Q

Why might the reported height and width of a page differ when looking cross browser?

A

Each browser has default stylesheets, and differences in those (such as line heights) may cause differences in the values.

60
Q

If you set a width / height to 200px, will it be 200px?

A

No - it may actually be slightly smaller/larger, the pixels will could be fractional. This is expected, but you must take this into account.

So - even though the CSS may say 200, you need to read the real values whenever you use them by using functions such as

.height()
.width()

and then making the changes.

61
Q

What are the main positioning jQuery functions?

A
.height()
.width()
.innerHeight()
.innerWidth()
.outerHeight()
.outerWidth()
.offset().top
.offset().left
.position().top
.position().left
62
Q

How can you store data on an element?

A

.data()

.data(key, value) // Set a key value key
.data(jsObject) // Can pass multiple values
.data(key) // return the value for this key

63
Q

What is the HTML5 standard for naming data?

A

data-[keyname]

64
Q

What function is used to remove data from an element?

A

.removeData()

65
Q

In jQuery, when dealing with data - do you need to provide the data- prefix?

A

No, jQuery deals with that.

66
Q

What method is now used (as of about JQuery 1.8) to bind events?

A

.on
.off

These replace the old bind, die etc methods.

67
Q

If you call .on like this:
$(“#evttarget”).on(“mouseover mouseleave”, myfunc);

How would you turn these events off?

A

$(“#evttarget”).off(“mouseover mouseleave”, myfunc);

NOTE: You pretty much have to call it the same way to turn off the events properly. Even including the function (because presumably, we are only turning off the binding between those events and THAT specific function.

68
Q

How would you write an event that grabs the users text input from the keyboard?

A
("#evttarget").on("keypress", function(evt) {
   // You can use the 
   // String.fromCharCode(evt.charCode) method to grab
  // the text, and insert it where you will...
});
69
Q

The hover event handler is setup how?

A

$(“#mydiv”).hover(highlight, highlight);

The same function is passed twice (in this case) because it is likely using a toggleclass method to add / remove the class that is responsible for adding the highlight.

70
Q

Normally you would add a new event handler by using the .on method - why are there also methods such as .hover, .click etc?

A

These are helper methods, there are a couple of helper methods that are added by jQuery to make every day tasks a little easier.

71
Q

What are the event handler helper methods provided by jQuery?

A

.hover
.click
.dblclick
.resize

(but there are plenty of others)

72
Q

What would you typically attach the .resize event handler to ?

A

The window.

$(window).resize(myhandler);

73
Q

Why does the jQuery event object exist?

A

Because, despite a standardisation of the event handlers across browsers, the way the data is passed is actually not standard, and can be inconsistent. jQuery actually provides a normalised event object to deal with that.

74
Q

What does the meta key property describe in the event object?

A

It’s the windows / mac key (or other key depending on system). It’s a boolean value.

75
Q

What properties are normalised in the event object?

A

target - what fired the event
relatedTarget
which - which key, mouse button (not always used)
pageX - Where the event occurred (not always used)
pageY
metaKey - Which special key (windows key etc)

76
Q

How do you pass data to an event handler so that you can keep track of things like which object was clicked?

A

$(“#Div1”).on(“click dblclick”, { name: “Div 1” }, function(evt) {});

You can pass (as the second parameter), data in the form of a json object

77
Q

What does the stopPropagation() method do?

A

You call this function on an event, so:

evt.stopPropagation(). It prevents the event from bubbling up through the hiearchy. If you have actually processed the event, there is no need to let it keep going, so calling this will stop it.

78
Q

Given a div that you have to highlight, as well as some of the contents, it may be tempting to use jQuery to highlight each element that you have to toggle on - but what is a more efficient way of doing this with CSS doing most of the heavy lifting?

A

You can use jQuery to toggle on the highlight for the parent container. Say a div with the class “event”.

.event { background-color: red; }

But then instead of explicitly highlighting the containing text, you can just have more CSS which is only enabled when the parent class is active (i.e. during that hover event)

.event .mytext { color: white; }

This way - only one jQuery call instead of having to find children to the parent etc.

79
Q

What is the difference between .toggle and toggleClass?

A

.toggle will toggle the visibility of the element, while toggleClass will toggle the given class of the element.

80
Q

What does the second parameter in the .show and .hide methods do?

A

It specifies an ease in/out method. There are two defaults, linear and swing. You can add new ones.

81
Q

How do you fade out / in an element?

A

$(“#element”).fadeIn(100);
$(“#element”).fadeOut(100);

NOTE: You can specify “fast” or “slow” too - values are in milliseconds

82
Q

How do you fade to a specific opacity level?

A

$(“#element”).fadeTo(100, 1.0);

Over 100 miliseconds - fade to 100% opacity.

83
Q

How could you create a “pulse” effect in animation?

A

$(“#element”).fadeTo(100, 0.3)
.fadeTo(100, 1.0)
.fadeTo(100, 0.3)
.fadeTo(100, 1.0);

NOTE: Because we are using statement chaining here, the functions will not fire until the previous one has finished. So it will appear to pulse.

84
Q

What functions can you use to make an object slide into / outof existence?

A

.slideUp
.slideDown
.slideToggle

85
Q

If you want to animate seperate animations at the same time (using the animation function), what is the key?

A

You have to specify the values together. Running them one of the other (or on two events that fire at the same time) will result in one of the events queueing.

86
Q

Animate a div 500px to the left, over 1000 milliseconds and with a “swing” easing style.

A

$(“#div”).animate({ left: “500” }, 1000, “swing”);

87
Q

What does the following do?

$(“#div”).animate({ left: “+=500” }, 1000);

A

The += sign adds 500px to the current position, rather than just animating to the 500px position.

88
Q

If you have to loop through a series of div’s - i.e. for an image rotator, how would you achieve this?

A
var curPhoto = $("#current");
var nextPhoto = curPhoto.next();
if (nextPhoto.length == 0)
   var nextPhoto = $("#images div:first");

i.e. if the result set from curPhoto.next() is zero, then find the first one in the set.

89
Q

What are some of the $.ajax functions that are used to deal with the return data?

A

.done
.fail
.always

90
Q

What helper function is provided to do a get request?

A

$.get(“url”, successFunction);

91
Q

What helper function is provided to do a get request, but place the data directly into a page element?

A

$(“#myelement”).load(“url”);

This will take the data from “url” and insert it into the element provided in the element selector.

92
Q

If we read an xml document via ajax, what functions can we use to parse that document?

A

The standard dom API. (Remember, HTML / XML share a common root)

.getElementByTagName
.getElementsByTagName
.firstChild.nodeValue

93
Q

If you have a tag called name, with text in it, how many nodes are there?

[name]Joe Bloggs[/name]

(these should be angle brackets - but brainscape sucks)

A

There are two. The text within the name node is itself a node. So when you are retrieving it…

var name = getElementsByTagName("name")[0];
var value = name.firstChild.nodeValue;

It might seem odd, but the text is the firstChild. You can’t just call “nodeValue” on the name field - as the text within it is it’s own node.

94
Q

What are AJAX global events?

A

They are events that allow you to register a function / handler such that an event (like an error) can be handled in a centralised place. You don’t have to add error handling functions to every single AJAX call, rather you register the handler - and it will be called whenever an error occurs.

95
Q

What functions are available for registering handlers for global AJAX events?

A
.ajaxComplete
.ajaxSend
.ajaxError
.ajaxStart
.ajaxStop
.ajaxSuccess
96
Q

Global events are fired on each ajax request if…

A

The value of “global” is set to true on the jQuery.ajaxSetup()

(which it is by default)

97
Q

Global events (no matter what the value of the variable “global” is) are never fired for…

A

cross domain scripts and JSONP requests.

98
Q

What is AHAH?

A

Asynchronous HTML and HTTP

When you use AJAX to grab a chunk of HTML from somewhere, and embed it on your page, you are using AHAH.

99
Q

What is the difference between JSON and JSONP?

A

JSON is used to send data around within your app - JSONP is JSON with padding and is designed for sending data to remote apps.

100
Q

Why is one variable preceded by a dollar sign, while the other is not?

var $results = $(‘#rep-lookup-results’),
zipcode = $(‘#txt-zip’).val();

A

$results is a jQuery object. The $ sign is used to denote this.

The variable zipcode is simply a text string from a dom object (we used “val()” to obtain the value of that dom object). And so should not have the $ sign.

101
Q

Many URL’s for API’s have a segment like ?callback=? why is this?

A

You may need to supply this in the url or else it will not respond with a JSONP object.