JavaScript

¡Supera tus tareas y exámenes ahora con Quizwiz!

Write the JQuery code for getting the number of characters in '.status-box'

$('.status-box' ).val().length;

Use jQuery to empty the 'status-box' class.

$('.status-box').val('');

When you click in the page's body, the next image fades in over 600 milliseconds: $('body').click(______ { $('.slide').______(600)._____('active-slide'); });

$('body').click(function() { $('.slide').fadeIn(600).addClass('active-slide'); });

When you click in the page's body, the current image fades out over 600 milliseconds: $('body').click(______() { $('.slide').______(600).____('active-slide'); });

$('body').click(function() { $('.slide').fadeOut(600).addClass('active-slide'); });

When you click in the page's body, the current image slides up over 600 milliseconds: $('body').click(function() { $('.slide').______(600).________('active-slide'); });

$('body').click(function() { $('.slide').slideUp(600).addClass('active-slide'); });

Use $( ) to select all p elements on the page.

$('p');

Use jQuery to select document

$(document)

__________ selects the whole web page.

$(document) selects the whole web page.

Use jQuery to select document. Add a .keypress() method with a function inside. This function is called a keypress event handler.

$(document).keypress(function(event) {...});

Add a listener to a button named btn

('.btn').click(function() {......});

List the following JQuery control methods: _____() hides the selected HTML element _____() displays an element _____() alternates hiding and showing an element _____() adds a CSS class to an element _____() removes a class from an element _____() alternates adding and removing a class from an element

.hide() hides the selected HTML element .show() displays an element .toggle() alternates hiding and showing an element .addClass() adds a CSS class to an element .removeClass() removes a class from an element .toggleClass() alternates adding and removing a class from an element

write JavaScript code to send an alert ('Key Pressed') each time a character was typed into a text field

<input type ="text" id= "typing" onkeyup="window.alert ('Key Pressed');"> NOTE: onkeyup: This occurs when the viewer lets go of a key on the keyboard releasing the key

Display "Hello World" in a paragraph on page with strong emphasis on Hello

<p><strong>Hello</strong>World</p>

How can you call external JavaScript code in your HTML?

<script type="text/javascript" SRC="yourfile.js> JavaScript code here.. </script>

How can you explicitly identify JavaScript as your scripting language in your HTML internally

<script type="text/javascript"> JavaScript code here.. </script>

Write code for webpage viewers browsing without JavaScript

<script type="text/javascript " src="file.is" ></script> JavaScript code here </script> <noscript>no script code here</noscript>

Write code to allow a page to continue to load without waiting for the script to load

<script type="text/javascript " src="file.is" async></script>

Write code to defer loading external script until page fully loaded

<script type="text/javascript " src="file.is" defer></script>

Write to a webpage the full URL of the current document.

<script type="text/javascript"> document.write(document.URL); </script>

Select all children of the <div class="article">..</div> element. Choose one of the following: A: $('.article').children(); B: $('h2 ul p'); C: $('li').text('children');

A: $('.article').children();

Create a new li element with the class "author", and append it to the ul element. Choose: A: $('<li>').addClass('author').appendTo('ul'); B:$('ul').appendTo('<li>').addClass('author') C: $('li').addClass('.author').appendTo('<ul>')

A: $('<li>').addClass('author').appendTo('ul');

Select li elements and replace text with "Empty List". Choose one of the following: A: $('li').text('Empty List'); B: $(li).text('Empty List'); C: $(<li>).text('Empty List');

A: $('li').text('Empty List');

Select all p elements on the page and hide them. Choose one of the following: A: $('p').hide(); B: $('.description').removeClass('p'); C: $('.p').hide();

A: $('p').hide();

An _____ _________ is a predefined JavaScript property of an object that is used to handle an event on a web page

An EVENT HANDLER is a predefined JavaScript property of an object that is used to handle an event on a web page

An operator is a ___word in JavaScript that enables a certain ____ between values

An operator is a KEYWORD in JavaScript that enables a certain CALCULATIONS between values

___ keyword refers to the current object

this keyword refers to the current object eg console.log( this.document === document); // true

What are the return values of the following: true&&true true&&false false&&true false&&false

true&&true=true true&&false=false false&&true=false false&&false=false

What are the return values of the following: true||true true||false false||true false||false

true||true=true true||false=true false||true=true false||false=false

Explain: typeof 37 === 'number'; typeof 3.14 === 'number';

typeof operator returns a STRING that tells you it's TYPE eg typeof 37 === 'number'; typeof 37 will return 'number'. This is compared to 'number' and returns true. DECIMAL numbers are also of type 'number'

Write code that hides the following <div id=about>The company was founded in 2002 by a group of college friends</div>

var aboutCo =document. getElementById("about"); aboutCo.style.display ="none"; To display the div aboutCo.style.display ="block"; Where block refers to the div content HTML element.

Get an array containing all the elements in the document that have the tag name img and store it in var name all_imgs

var all_imgs=document. getElementsByTagName ("img");

Using an array literal - Create an array called answers that contains the elements: 15 Friday -76

var answers = [15,"Friday",-76]; This is an array that contains the elements

Create an array called answers that contains the elements: 15 Friday -76

var answers = new Array(15,"Friday",-76); An array can store different data types

complete the following JavaScript called so that when "btn1" is clicked, the event type would be alerted to the user var b1= document.getElementById("_____ "); b1._____ = function(_____ ) { alert("The "+_____ ._____ +" event started this!");};

var b1= document.getElementById("btn1"); b1.onlick = function(event) { alert("The "+event.type +" event started this!");}; The type property of the event object is used to display an alert to the viewer

to implement the event object cross browser complete the following code: var b1= document.getElementById("btn1"); b1.onlick = function(event) { var ___ = _____|| _____.event; alert("The "+______.type +" event started this!");};

var b1= document.getElementById("btn1"); b1.onlick = function(event) { var e = event || window.event; alert("The "+e.type +" event started this!");}; Notice that the variable is assigned to the EVENT object if it is available on the WINDOW.event object if not. The use of the logical or operator (||) allows you to provide preferred value if it is available on the default is not

Write a variable called counter that holds integer 10 in JavaScript

var counter = 10;

Create a var named counter

var counter;

Update the '.counter' element to show the var curNum =140;

var curNum =140; $('.counter').text(curNum );

Staff object has three properties name salary and grade. var curStaff = new Staff("John", 30000, 5); Change the salary of John to be 35000.

var curStaff=new Staff("John", 30000, 5); curStaff.salary=35000;

Using JQuery: Make the next dot the active dot when the user presses the slider e.g. <.....">" var currentDot = $(_______); var nextDot = currentDot.____(); currentDot._______('active-dot'); nextDot.______('active-dot');

var currentDot = $('.active-dot'); var nextDot = currentDot.next(); currentDot.removeClass('active-dot'); nextDot.addClass('active-dot');

Create two variables for the currentSlide and the nextSlide. The currentSlide should select the active slide, and the nextSlide should store the next slide.

var currentSlide = $('.active-slide'); var nextSlide = currentSlide.next();

You have a HTML div element who's ID is div1 ie <div id="div1">hello world</div> use JavaScript method to change the color of div element div1

var d1= document. getElementById("div1"); d1.style.color="#DDDDDD";

Write code in JavaScript so that when a user clicks the mouse the background color of a div element who's id is "div1" will be changed to #DDDDDD ie light grey color

var d1=document. getElementById("div1"); d1.onclick=function (){d1.style. backgroundColor="#DDDDDD"};

The HTML code has a set of radio buttons all named dino - get all of the elements within this radio button named dino

var dino_radio_array= document. getElementsByName("dino ");/* to print all the elements*/ for (var i=0;i< dino_radio_array. length){document.write( dino_radio_array[i]);}

Create a new li element and append it to the ul element. Choose one of the following: A: $(<li>).appendTo('ul'); B: $('<li>').appendTo('ul'); C: $('<li>').append('ul');

C: $('<li>').appendTo('ul');

Select all p elements and remove them. Choose one of the following: A: $('<p>').remove(); B: $('p').delete(); C: $('p').remove();

C: $('p').remove();

Select the ul element and add the class "attribution". Choose one of the following: A: $('ul').text('.attribution'); B: $('.attribution').appendTo('ul'); C: $('ul').addClass('attribution');

C: $('ul').addClass('attribution');

create a new p element and add the words "New Items" to it. Choose one of the following: A: $('p').text("New Items"); B: $('<p>').text('New Items'); C: $(<p>).text('New Items');

C: $(<p>).text('New Items');

The not equal to operator is A: !=== B: ===! C: != D: !==

D

Web pages made with HTML and CSS display dynamic content. True or false?

False: Web pages made with HTML and CSS display static content.

A var declared globally can only be used in certain parts of your JavaScript code defined by its scope: True or False

False: a global var can be called ANYWHERE in your code I.e. inside functions and any where else

Explain line 3: 1 var main = function() { 2 $('.dropdown-toggle').click(function() { 3 $('.dropdown-menu').toggle(); 4 }); }

If clicked, the dropdown menu will appear and if you click the mouse on the top of the drop down menu, it will disappear.

explain the following code: $('.btn').click(function() { $('<li>').text('New item').prependTo('.items'); });

The $() function creates a NEW li ELEMENT. Text is ADDED to the NEW li element. The li element is added as the FIRST ITEM inside <ul class="items"> .. </ul> on the page.

The _______ method lets you create your own custom animations.

The .animate() method lets you create your own custom animations.

The ______ method gets the previous sibling of the selected element.

The .prev() method gets the previous sibling of the selected element. e.g. $('.description').prev();

The operator to compare value is A: ==? B: == C: === D: = E: ?=

C

It's best to keep keep global variables to a minimum. True or False

True: declaring global variables guess against the principals of REUSABILTY and COHESIVE code DESIGN

Javascript forces you to declare the type of a variable eg String one ="hello"; Double Two=10.0; True or False

False: JavaScript dues NOT force you to declare the type of variable eg var one="hello"; var two=10.0;

Javascript object values can store only primitive data types. True or false

False: Javascript object values can store ANY data types eg method functions arrays primitive data types objects

A function constructor creates a function OBJECT the same as creating a new instance of an object. True or false

True: drawback is a function constructor is EVALUATED every time it is used.

Javascript object values can store any data type. True or false

True: eg method functions arrays primitive data types objects

Write a JavaScript function called hello_world that prints a paragraph Hello World

function hello_world(){ document. write( <p>Hello World</p>); }

Write a JavaScript function called sum that returns the sum of two numbers passed as parameters

function sum (var1, var2){ var result= var1+var2; return result; } ..... /*stores 35*/ var curResult=sum (34, 1);

Webpages can respond to user's actions: true or false?

True

Write JQuery called so that when you click in the page's body, the next image 'slide' down over 600 milliseconds.

$('body').click(function() { $('.slide').slideDown(600).addClass('active-slide'); });

var n=n+2; is equivalent to var n +=2; True or false

True: += is an assignment operator that ADDS the value on the right side of the operator to the value on the left and STORES it in the value on the LEFT

What's the code to run the main() JavaScript function?

$('document').ready(main);

Explain the following code: $(document).keypress(function(event) { .................. });

$(document) selects the whole web page, and the .keypress() method attaches an event handler to document. Inside the body of the event, something happens when a key is pressed on the page

yields, within, ints, lets, debug are valid variable names. True or False

True: All are valid variable names

Variable's can be used before they are declared. True or False

True: JavaScript INTERPRETER scans FORWARD to inspect declarations

if (1>2) return true? return false;

Result will return false

Inside the main function, use jQuery to select the class 'icon-menu'.

var main = function() { $('.icon-menu').click(function() {}); };

#1Fill in the blanks <form><input ____="button" ___="Launch" id="say_hi"></form> <script type="____/____" src="_____"></script>#2 Write a JavaScript event handler inside a file js_main.js which prints two alert windows that state "Launch" "Complete" every time the "Launch" button is pressed

#1 <form><input type="button" value="Launch" id="say_hi" ></form><script type="text/javascript" src="js_main.js"></script> #2 inside js_main.js: var hi_button = document.getElementById("Launch"); hi_button.onclick =function(){ window.alert('Launch'); window.alert('Complete'); }

Give 1 or more eg's of each of the following operators: #1 Arithmetic #2 Assignment #3 Comparison #4 Logical #5 Bitwise

#1 Arithmetic: +,-,* #2 Assignment: = #3 Comparison: ===,>,< #4 Logical: && (AND) #5 Bitwise: << (Shift left) (Works at bit level zeros and ones)

Name two drawbacks for having unused functions in your code?

#1 DIFFICULT to MAINTAIN #2 INCREASES DOWNLOAD time for viewers

explain the following events: onkeydown onkeypress onkeyup

#1 onkeydown : occurs when the viewer presses down a key on the keyboard#2 onkeypress : occurs when the viewer presses down a key on the keyboard and the corresponding characters typed. This occurs between the key down and key up presents. #3 onkeyup: This occurs when the viewer lets go of a key on the keyboard releasing the key

Explain: #1 typeof "bla" #2 typeof true #3 typeof Symbol('foo') #4 typeof {a:1} #5 typeof blabla

#1 returns 'string' type #2 returns 'boolean' type #3 returns 'symbol' type #4 returns 'object' type #5 returns 'undefined' type

.click() method attaches an event handler to each button. Give an example of this code

$('.SOME-ELEMENT').click(function() { ......... });

Using JQuery: Make the previous dot the active dot when the user presses the slider e.g. "<".....> $('.arrow-prev').click(function(){ var currentSlide = $(______); var prevSlide = currentSlide._____; currentSlide.______(600).removeClass(______); prevSlide.____(600).addClass(_____); }

$('.arrow-prev').click(function(){ var currentSlide = $('.active-slide'); var prevSlide = currentSlide.prev(); currentSlide.fadeOut(600).removeClass('active-slide'); prevSlide.fadeIn(600).addClass('active-slide'); }

Use $( ) to select the h2 element nested inside the <div class="article">..</div> element.

$('.article h2');

write an event handler so that when an article class is clicked, it's description is hidden.

$('.article').click(function() { $('.description').hide(); });

write an event handler so that when an article class is clicked, make sure it's nested description class contents are shown

$('.article').click(function() { $(this).children('.description').show(); });

write a JQuery to disable the button btn

$('.btn').addClass('disabled');

Write code so when 'btn' button element is clicked the 'selected' element is deleted from webpage

$('.btn').click(function() { $('.selected').remove(); });

Write JavaScript code to take text from status-box and post it into another 'post' class when the user clicks the post button 'btn'

$('.btn').click(function() { var post = $('.status-box').val(); $('<li>').text(post).prependTo('.posts'); });

write to JQuery code to listen for when the user this is finger from the key having pressed on the btn

$('.btn').keyup(function() { });

write a JQuery to enable the button btn

$('.btn').removeClass('disabled');

use the animate method to set the width of the menu to 193 for a duration of 300 ms: $('.icon-menu').____(_____() { $('.menu')._____({ ___: "193px" }, ____); });

$('.icon-menu').click(function() { $('.menu').animate({ width: "193px" }, 300); });

Use $( ) to select only the <li class="pubdate">..</li> element.

$('.pubdate');

You have the following HTML <body><div id="About_Div" title="About me blah">This is about me.....</div></body> Using DOM Node methods - add another div element underneath the above div element that has a div title called "Me Two" and containing the div text "More about me"

/*GET the PREVIOUS div ELEMENT*/ var me_div= document.getElementById("About_Div");/*CREATE a NEW DIV ELEMENT*/ var inner_div=document.createElement("div"); /*create TEXT for the NEW DIV ELEMENT*/ var inner_div_text=document.createTextNode("More about me");/*ADD a TITLE to the NEW DIV ELEMENT*/ inner_div.title="Me Two"; /*ADD TEXT to NEW DIV ELEMENT*/inner_div.appendChild( inner_div_text); /*ADD the NEW element to About_Div element*/ me_div.appendChild(inner_div);

Below is a function object constructor called Staff. Create a method (method prototype) that will be shared among all instances of Staff that gives a description of Staff name salary and grade of the object instance. function Staff(aName, aSalary, aGrade){this.name= aName; this.salary= aSalary; this.grade= aGrade; }

/*create prototype method called description for all instances of Staff*/ Staff.prototype.describe = function(){ document.write(this. name); document.write(this.salary); document.write(this.grade); } /*Create a Staff instance and assign prototype method description to it*/ var document.write(this.salary); var employee1 =new Staff( "Mark", 45000, 6); /*Will print all details of this Staff instance to webpage commonly called CONSTRUCTOR/PROTOTYPE PATTERN*/ employee1.description();

explain the following code: $('.article').click(function() { $('.article').removeClass('current'); $('.description').hide(); $(this).addClass('current'); $(this).children('.description').show(); });

/*event handler listens for articles clicked*/ $('.article').click(function() { /*remove previous left clicked item*/ /* as the current article*/ $('.article').removeClass('current'); /*hide it's description*/ $('.description').hide(); /*assign the current left clicked /* item as the current article*/ $(this).addClass('current'); /*show the current left clicked */ /*article description*/ $(this).children('.description').show(); });

explain each line of the following code: $(document).keypress(function(event) { if(event.which === 110) { var currentArticle = $('.current'); var nextArticle = currentArticle.next(); currentArticle.removeClass('current'); nextArticle.addClass('current'); } });

/*key press event listener */ $(document).keypress(function(event) { /*110 represents the n key */ if(event.which === 110) { /*get the currently click the article */ var currentArticle = $('.current'); /*to get the next article in the list below */ var nextArticle = currentArticle.next(); /*remove the old linked article above */ currentArticle.removeClass('current'); /*assign the current article the next article */ nextArticle.addClass('current'); });

explain each line of the following code: $(document).keypress(function(event) { if(event.which === 111) { $('.description').hide(); $('.current').children('.description').show(); }

/*key press event listener */ $(document).keypress(function(event) { /*111 represents the key o */ if(event.which === 111) { /*hide the previous description */ $('.description').hide(); /* get the newly clicked item and show description */ $('.current').children('.description').show(); }

The array pop() function removes and returns the last element in an array? True or father

/*removes orange and stores it in var curFruit*/ var fruits = ["Banana","Orange"]; var curFruit =fruits.pop(); /*adds kiwi to end of array*/ fruits.push("Kiwi");

identify three mistakes to make code work: 1 var main = function() { 2 $('.dropdown-toggle').click() { 3 ('.dropdown-menu').toggle(); 4 }); 5 }; 6 (document).ready(main);

1 var main = function() { ->2 $('.dropdown-toggle').click(function() { ->3 $('.dropdown-menu').toggle(); 4 }); 5 }; ->6 $(document).ready(main);

Explain the following code: 1: $(document).keypress(function() { 2: $('.dropdown-menu').toggle(); });

1: $(document) selects the whole web page. The .keypress() method attaches an event handler to document. 2: When any keyboard key is pressed, the event handler toggles the dropdown menu.

jQuery enables us to do three main things on a web page......

1: Events. RESPOND to user interactions. 2: DOM Manipulation. MODIFY HTML ELEMENTS on the page. 3: Effects. Add animations.

explain the two main uses of $( )

1: SELECT EXISTING HTML ELEMENTSon the page. e.g. $('p') selects all p elements on the page. 2: To CREATE NEW HTML ELEMENTS to ADD to the page. e.g. $('<h1>') creates a new h1 element. The < > indicates that we want to create a new HTML element.

What is the value of tweetlen? var tweet = "trip"; var tweetlen = tweet.length;

4

Completes the following JavaScript code so that when the user hovers over a link, and alert would appear to state "please click me": <a href ="www.CIT.ie" MISSING CODE="MISSING CODE">CIT </a >

<a href ="www.CIT.ie" onmouseover="window.alert ('please click me');">CIT </a > NOTE: onmouseover occurs when a viewer moves the mouse cursor over an element

Write code so that when a user hovers their mouse over the link www.rte.is an alert will appear starting "Safe Link"

<a href="www.rte.ie" onmouseover="window.alert('Link Safe');">RTE Website</a>

Write code to show an alert when a webpage has finished loading

<body onload="window.alert('page finished loading');">....</body> onload handler is added to the body tag

Write code so that when a user decides to leave the current page an alert appears to state "call back soon"

<body onunload="window.alert('call back soon');">Other HTML code goes here.....</body>

How can you prevent the "server not found error"in the following JavaScript code: <body><a href="http://none" onclick="window.alert('link clicked');">press here</a></body>

<body><a href="http://none" onclick="window.alert('link clicked'); return false;">press here</a></body> The return false statement prevents the browser from trying to open the link.

Write the title of the HTML document in the main body of the webpage

<body><script type="text/javascript"> document.write(document.title); </script></body>

Explain Event Capturing

<div class="d1">1 <!-- the topmost --> <div class="d2">2 <div class="d3">3 <!-- the innermost --> </div> </div> </div> The Capturing guarantees that click on Div 3 will trigger onclick first on the TOPMOST ELEMENT 1 then on the element 2, and the last will be element 3. Then it BUBBLES back up

Explain Event Bubbling.

<div class="d1">1 <!-- the topmost --> <div class="d2">2 <div class="d3">3 <!-- the innermost --> </div> </div> </div> The bubbling guarantees that click on Div 3 will trigger onclick first on the INNERMOST ELEMENT 3 (also called the target) then on the element 2, and the last will be element 1.

Write code that asks you to enter your name into a text box and when you press an submit button - an alert will appear stating "thank you "

<form onsubmit="window.alert('Thank You');"> What's your name?<br> <input type="text" id="thename"><br> <input type="submit" value="Submit Form"></form>

Write code that contains a button which displays "Launch" so that when the button is clicked then two window alerts are displayed with the words "Launch Complete" and "The end".

<form><input type="button" value="Launch" onclick="window. alert('Launch Complete'); window.alert('The end'); " </form> onclick is the event handler. The ';' separate the JavaScript statements.

Write code that contains a button which displays "Launch" so that when the button is clicked then a window alert is displayed with the words "Launch Complete"

<form><input type="button" value="Launch" onclick="window. alert('Launch Complete');" </form> onclick is the event handler

Create code so that there are two text boxes: The first asks user "Enter First Name" and the second asks user "Enter Surname". When the user clicks the "Enter Surname" text box the first text box loses focus and alert window appears to state "First Name Blurred"

<form>Enter First Name:<br><input type="text" onblur="window.alert('First Name Blurred');"><br> Enter Surname: <br> <input type="text"></form>

Write code so that before a user types his name into a text box, an alert will appear reminding user not to forget to capitalise. Here the skeleton code: <form>Enter Your Name: <input MISSING CODE HERE > </form>

<form>Enter Your Name: <input type="text" onfocus="window.alert('Don\t forget to capitalise!');"> </form> The ONFOCUS event handler will assist the viewer before typing into text box to capitalise first

The _____ property returns the URL of the document without any encoding eg if there is a filename with a space the property will return the space rather than a %20 in its place. Write code to print the full URL name with spaces included if the current document

<script type="text/javascript"> document.write(document.URLUnencoded); </script>

Write a var car="mustang"; using document.write ()

<script type="text/javascript"> var car="mustang"; document.write(car); </script>

Add a number 2 to a string "1"

<script type="text/javascript"> var one="1"; document.write(one+2); </script> Will print "12"

Write to the screen hello world in JavaScript

<script> document.write("Hello World "); </script>

Write code to make a browser to go back to the previous page that was viewed

<script>navigator.history.back()</script> history is a predefined JavaScript object which is located in window.navigator.history

Write code to make a browser to go forward to the previous page that was viewed

<script>navigator.history.forward</script> history is a predefined JavaScript object which is located in window.navigator.history

A _____ skips all other statements below it INCREMENTS the next iteration of a loop

A CONTINUE skips all other statements below it INCREMENTS the next iteration of a loop

What are the return values of the following A 4!=4 B "4"==4 C "3"===3 D "3"!==3

A False B TRUE C False D False

A ____ _____ occurs when a user clicks on an HTML element.

A click event occurs when a user clicks on an HTML element.

What's the difference between a while loop and a do/while loop?

A do/while loop executes AT LEAST ONCE

Variable names must begin with ____ or ______ or ______

A letter or underscore _ or dollar sign $

What are the return values of the following: A true>0 B "a">"A" C false>0

A true (boolean value true converted to 1 B true (a is 97 char code and A has 65 char code) C false (boolean value of false converted to 0)

List the attribute nodes and child nodes of the following HTML: <body><h1>my page</h1><img src="myimg.jpg" alt="My Picture"></body>

Attribute nodes: src="myimg.jpg" alt="My Picture" child nodes: List the attribute nodes and child nodes of the following HTML: <h1>......</h1><img ......>

Which one of the following a) or b) changes the background color of div element named "div1"? var d1=document. getElementById("div1"); d1.style. a) background-color="#DDDDDD"; b) backgroundColor="#DDDDDD";

B) is correct. a) won't work because JavaScript DOESN'T ALLOW the hyphen (-) as part of a PROPERTY NAME. Instead JavaScript PUTS BOTH WORDS TOGETHER and CAPITALISES the FIRST LETTER of any ADDITIONAL word

Get the text within header. Choose one of the following: A: $(<h1>).text(); B: $('h1').text(); C: $('h1').getText();

B: $('h1').text();

Select all children of the ul element. Choose one of the following: A: $(ul).children(); B: $('ul').children(); C: $('.source');

B: $('ul').children();

Give the operator order of preference

BPUCMASREBBLLTA BRACKETS () POSTFIX a++ b-- UNARY ++a (-c) ! typeof CASTING (String) new MULTIPLICATION * / % ADDITION + - SHIFT >> << >>> RELATION == != === in instanceof BITWISE & BITWISE ^ | LOGICAL && LOGICAL || TERNARY ASSIGNMENT = \= *= +=

____ stops the loop at a particular point and exits the loop

BREAK stops the loop at a particular point and exits the loop

var fruits = ["Banana","Orange", "Apple","Mango"]; var v = fruits.valueOf(); What's the output?

Banana,Orange,Apple,Mango

Select the <p class="description">..</p> <p>Hello</p> and remove the class "description". Choose one of the following: A: $('description').removeClass('.description'); B: $('.p').remove('description'); C: $('.description').removeClass('description');

C: $('.description').removeClass('description');

var fruits = ["Banana","Orange", "Apple"]; fruits.shift(); Result of advice will be: A: apple banana orange B: banana orange C: orange apple

C: orange apple Remove the FIRST ITEM of an array.

How can you correctly sort number elements in an array?

Create a COMPARISON function: function mySort(firstVal, secondVal){ if ( firstVal> secondVal){ return 1; } else if ( firstVal< secondVal){ return -1; } else { return 0;} } var fruits= [2,3,1,20]; fruits.sort(mySort); Output: 1,2,3,20

Explain: myobj = { h: 4, k: 5 }; delete myobj.h;

Delete an object or property or element (in a global array) /*Global object*/ myobj = { h: 4, k: 5 }; /* h is a property of the global object myobj and can be deleted returns true */ delete myobj.h;

Every function in JavaScript has what is known as a ____ property. This is an object that contains properties and methods that are about always available for each instance of an object.

Every function in JavaScript has what is known as a PROTOTYPE property. This is an object that contains PROPERTIES(variable) and METHODS that are about always ACCESSIBLE for EACH INSTANCE of an object. Think of it like a STATIC VARIABLE or METHOD in JAVA

The following JQuery will compile. True or False? $('.arrow-prev').click(function(){ /*some code */ }

False. Missing missing ); at the end: $('.arrow-prev').click(function(){ /*some code */ });

This code will not compile. True or False? var main = function() { }; $(document).ready(main);

False. compiles okay

The array method join() jobs two arrays together. True or false

False: 'joins' the array elements together into a string eg var fruits = ["Banana","Orange"]; var energy = fruits.join();

A function constructor creates a function method. True or false

False: A function constructor creates a function OBJECT the same as creating a new instance of an object.

The following will give compile error: var one='hello'; var two="world "; True or false

False: Both single ' ' and double quotes " " pairs can be used for string values.

The following will give errors: var score1 = 1; var score2 = 2; var result = score1/score2;

False: Compiles and runs fine

DOM Level 0 contains the following event handlers: onclick onmouseover and addEventListener() true or false?

False: DOM Level 0 contains the following event handlers: onclick onmouseover onmousedown onmouseup onmouseenter onmouseleave onmouseover onmouseout onmousemove onwheel. DOM Level 1 contains: addEventListener() and attachEvent(). DOM Level 2 offers the ability to attach MULTIPLE EVENTS to elements. In contrast DOM Level 0 allows ONE EVENT to be REGISTERED on any given element

A function cannot be called before it is declared. True or fake

False: JavaScript INTERPRETER scans FORWARD to inspect declarations

The following code will print "link clicked" in an alert box when the link is clicked and close. True or False? <body><a href="http://none" onclick="window.alert('link clicked');">press here</a></body>

False: The alert will work but the browser will try to open the link and state "Server not found error".

yield, with, in, let, debugger are valid variable names. True or False

False: all are keywords in JavaScript

var continues =3; will give a compile error. True or false

False: continues is a valid valid variable name. However continue is a keyword in JavaScript JavaScript

The following JavaScript code will print: Hamlet says, "to be, or not to be". document.write("Hamlet says, " to be, or not to be" "); True or false

False: extra quotes at end will cause error. Placing \ shows fur under quotes to become part of the string document.write("Hamlet says, \" to be, or not to be\" ");

var integer, double; will give a compile error. True or False

False: integer and double are valid variable names. However int is a keyword and not a valid variable name

The function expression can use function declaration hoisting?

False: it's an anonymous function an only used once. Cannot execute until defined.

lastIndexOf([string]) searches an array from front to back and indexOf([string]) searches an array from back to front. True or false

False: lastIndexOf([string]) searches an array from BACK to FRONT and indexOf([string]) searches an array from FRONT to BACK. True or false

The below code will print two alerts when the user clicks the mouse over mydiv elements. True or false? var mydiv = document.getElementById("mydiv"); mydiv.onlclick = function() { alert(" First Click!");} mydiv.onlclick = function() { alert(" SecondClick!");}

False: mydiv element will overwrite the first one so only the "Second Click!" alert will be displayed when the click occurs. NOTE: this is because onlclick DOM Level 0 only allows ONE EVENT to be REGISTEREDon any given element

The following code will give errors: var p1=["Pretty","Poly"]; var p2= ["loves","Paul"]; var result=p1. concat(p2, 2, "day"); True or false

False: output is: Pretty Polly loves Paul 2 day

The 'with' statement is an efficient method of retrieving properties from objects. True or false

False: the use is often discouraged as there are PERFORMANCE DRAWBACKS eg global var accidentally assigned

JavaScript if statements and if/else blocks are different in syntax to Java. True or False

False: they are the same e.g. if( myName.length >= 7 ) {} else {}

The properties of the navigator object can be changed. True or false

False: they cannot be changed as they are READ ONLY

if (4=="4") {window.alert(true);} This will not print true? True or false

False: type coercion CONVERTS the string "4" into number and then compare a the number to return true

Unary negation is the ability to subtract numbers. True or false

False: unary negation is the ability to explicitly write a negative number eg var num= -3

The following code will print 0. var visa; document.write(visa); True or false

False: visa is null therefore code will not work as expected

document.write( "he says: 'Hello' ."); will give compile error. True or false

False: will print: he says:'Hello'. Using single quotes inside double quotes is OK and visa versa

var fruits= ["oranges","apples","pears","grapes"]; var someFruits= fruits.slice(1,3); SomeFruits will store apple pear grapes. True or False

False: will store apples pears I.e. slice(1,3) = slice array from array index 1 to index 3-1(2)

var fruits = ["banana","Orange", "apple"]; fruits.sort(); The result of fruits will be: apple,banana, Orange True or false

False: with the orange capitalised the order is as follows: Orange apple banana

Consider the following function: function checkBalance(num){ Window. alert( "Account "+ num+" balance is "+12345); } Then call checkBalance(); Will give error. True or False

False: you can call function without its parameters. Will print undefined but will still run

only double quotes (" ") can be used to write a string. True or False

False; Single quotes (' ') or double quotes (" ") can be used to write a string e.g var tweet = "Hiking trip on Saturday";

Explain line 2: 1 var main = function() { 2 $('.dropdown-toggle').click(function() { 3 $('.dropdown-menu').toggle(); 4 }); }

First, the code SELECTS the <a class="dropdown-toggle">..</a> element. Next, the code CHECKS whether this HTML element has been CLICKED. If it has been clicked, the line of code inside the curly braces will run (Line 3-4)

Name two advantages of placing JavaScript in external file as opposed to internally in header or body

If JavaScript code (variables and functions etc) declarations placed in HEAD tags then it may need to use INFO from the DOCUMENT that may NOT be LOADED yet. If JavaScript code declared in BODY then DIFFICULT to MAINTAIN.

Explain the following HTML and accompanying JavaScript code: <body><div id="div1">what is 2+2?</div><div id="div2"><a href="answer.html" id="answer_link">Get the Answer</a></div></body>JavaScript code: var d1=document. getElementById("div1"); var ans=document. getElementById("answer_link"); ans.onclick = function (){d1.innerHTML = "Answer is 4!"; return false;}

If the answer_link if pressed then the text "what is 2+2?" In HTML div1 gets replaced by "Answer is 4!"

explain line 4: 1 var main = function() { 2 $(".dropdown-toggle").click(function() { 3 $(".dropdown-menu").show(); 4 }); };

If the drop down menu is clicked, it will not disappear remain permanently open. If you change a line 3 to the following JQuery statement and if you click the mouse on the top of the drop down menu, it will disappear. $(".dropdown-menu").toggle();

Name ove benefit of anonymous function

In EVENT handling eg button listener etc

in Internet Explorer to access the event object you call the _____.event

In Internet Explorer to access the event object you call the window.event e.g. var b1= document.getElementById("btn1"); b1.onlick = function(event) { alert("The "+window.event.type +" event started this!");};

In most browsers the event object is accessed by using the name _____

In most browsers the event object is accessed by using the name EVENT. It can be passed as the lone argument to a function that handles the event

What's the method call to prevent the default action on an event link using JavaScript DOM Level 0

event.preventDefault()

Write code that contains a button which displays "Launch" so that when the button is clicked then two window alerts are displayed with the words "Launch Complete" and "The end". Use a function to call the window alerts

Inside a separate file called my_event.js write: function launchIt(){ window.alert('Launch Complete'); window.alert('The end');} Then inside the HTML code write: <form><input type="button" value="Launch" onclick="launchIt();" </form><script type="text/javascript" s c="my_event.js"></script> onclick is the event handler.

Write code in a separate script called load_alert.js to show an alert when a webpage has finished loading

Inside load_alert.js: window.onload = function(){ window.alert('I\'m loaded');}; Inside HTML: <body><script type="text/javascript" src="load_alert. js"></script>

var alpha =["a","b","c","d"]; var s1=alpha. splice(2,1,"z"); what is the output of s1?

Item at index 2 gets replaced by the value z therefore array s1 AND alpha now contains ["a","b","z","d"];

What two languages make webpages more interactive?

JavaScript and jQuery are used to make web pages interactive.

JavaScript is a _______ ______ used to add _______to a web page. jQuery _____ JavaScript syntax and makes it _____to build ______web pages that work across multiple browsers.

JavaScript is a PROGRAMMING LANGUAGE used to add INTERACTIVITY to a web page. jQuery SIMPLIFIES JavaScript syntax and makes it EASIER to build INTERACTIVE web pages that work across multiple browsers.

JavaScript is a programming language used to create web pages that _____in response to ____ actions.

JavaScript is a programming language used to create web pages that CHANGE in response to USER ACTIONS.

Explain type coercion

Javascript attempts to change the data type of a cake when it is deemed necessary eg var n1=2.67, n2=2; var sum=n1+n2; window.alert(sum); Answer shown in decimal ie 4.67

Javascript objects are basically a collection of ______ and ______ what's called a _____ ______ in programming

Javascript objects are basically a collection of PROPERTIES and VALUES what's called a HASH TABLE in programming

var fruits = ["Banana","Orange", "Apple"]; fruits.unshift("Lemon","Pineapple"); What is the output of the above?

Lemon pineapple banana orange apple ADDS the ITEMS to START of array

How can you get an alert pop up window to assist once the page is loaded?

Make sure the script is called just before the closing</body> tag eg <script type="text/javascript" src="alert.js"> </script></body>

Is there anything wrong with the following code? var b1= document.getElementById("btn1"); b1.addEvent(onlick, function(event) { alert("The "+window.event.type +" event started this!");} false);

No

Is there anything wrong with the following code? var b1= document.getElementById("btn1"); b1.addEventListener("click", function(event) { alert("The "+window.event.type +" event started this!");} false);

No

Explain the following mouse events: onmousedown onmouseup onmouseenter onmouseleave onmouseover onmouseout onmousemove onwheel

ONMOUSEDOWN: press button down and hold ONMOUSEUP: release button ONMOUSEENTER: move cursor over element ONMOUSELEAVE: move cursor away from element ONMOUSEOVER: move most cursor over element ONMOUSEOUT: move cursor away from element ONMOUSEMOVE: move the mouse cursor ONWHEEL: scroll mouse wheel up or down

Name the operators and operands in the following code: var sum= 1+"two"+3;

OPERATOR: + OPERANDS: 1, "two", 3 Notice operands are different of type ie string and number. Result will be string " 1two3"

What is the output of the following: for (var i=0; j=10; i<2; i++; j+=10;){ document. write (j+"<br>");}

Output is: 10 20 30 This is a multiple statement

What's the output of the following code: var k=0; while (k<3){ document. write("Hello!<br>"); K++;} document. write("Says Mrs. Doyle");

Output is: Hello! Hello! Hello! Says Mrs. Doyle

What's the output: var k=0; do { document.write ("knock "); K++; while (k<3); document.write ("<br> Who's there?");

Output is: Knock knock knock Who's there?

What is the output: var sum=11%2; window.alert(sum);

Output will be 1 Dividing 11 by 2 gives 5 with remainder of 1

What is the output: var sum=2/0; window.alert(sum);

Output will be special value of INFINITY

What will be the output after the following code is executed: function pass_grades(item_value, item_index, arr_name) {return ( item_value>=70);} var grades=[74,65,71]; var result=grades.some(pass_grades); window.alert(result);

Output will be true as the grade array needs to have AT LEAST one of the grades to be greater than 70

What is the output: var sum="From three "+2+3; window.alert(sum);

Output will be: "From three 23"

What is the output: var sum="2"-"1"; window.alert(sum);

Output will be: 1 JavaScript COERCED STRING into NUMBERS and THEN performed ARITHMETIC OPERATION subtraction

What is the output: var num1=2, sum=num1++; window.alert(sum);

Output will be: 2 The POSTINCREMENT occurs AFTER ASSIGNMENT to var sum

What is the output: var num1=2, sum=++num1; window.alert(sum);

Output will be: 3 The PREINCREMENT occurs FIRST before ASSIGNMENT to var sum

Representing nested tags in a HTML document as a UML like hierarchy structure is commonly referred to as _______

Representing nested tags in a HTML document as a UML like hierarchy structure is commonly referred to as Document Object Model (DOM).

What's the output of the following: var num=100; var num %=2;

Result is 0 as there's no remainder when dividing 100 by 2

____ mode is a way to opt in to a restricted variant of JavaScript.

STRICT MODE is a way to opt in to a RESTRICTED VARIANT of JavaScript. Browsers NOT SUPPORTING strict mode will run strict mode code with DIFFERENT behaviour from browsers that do. Strict mode applies to ENTIRE scripts or to INDIVIDUAL functions. It doesn't apply to block statements enclosed in {} braces;

Create and assign a variable (property) called "company" and assign value "MacDonalds" that is accessible to all instances of the following constructor function: function Staff(aName, aSalary, aGrade){ this.name= aName; this.salary = aSalary; this.grade = aGrade;}

Staff.prototype.company = "MacDonald's"; This adds the the prototype variable to ALL instances of Staff.

what's the difference between $('li') and $('<li>') ?

The $('<li>) function creates a NEW li ELEMENT. $('li') is used to select EXISTING li ELEMENTS on the page

Explain the following code: $('.btn').click(function() { $('<li>').text('New item').appendTo('.items'); });

The $() function creates a NEW li ELEMENT. Text is ADDED to the NEW li element. The li element is added as the LAST ITEM inside <ul class="items"> .. </ul> on the page.

Explain line 6: 1 var main = function() { 2 $('.dropdown-toggle').click(function() { 3 $('.dropdown-menu').toggle(); 4 }); 5 }; 6 $(document).ready(main);

The $(document).ready() WAITS for the HTML document to LOAD completely before running the main() function. JavaScript should ONLY RUN AFTER the web page has LOADED completely in the browser - otherwise there wouldn't be any HTML elements to add interactivity to.

Explain the .appendTo() method with e.g.

The .appendTo() method adds HTML elements to the end of the selected element. e.g. $('.btn').click(function() { $('<li>').text('New item').appendTo('.items'); });

The _________method gets the children of the selected element.

The .children() method gets the children of the selected element. e.g. $('.article').children();

The ________ method shows the selected HTML element by fading it in.

The .fadeIn() method shows the selected HTML element by fading it in.

The _______ method hides the selected HTML element by fading it out.

The .fadeOut() method hides the selected HTML element by fading it out.

The __________ method attaches an event handler to an HTML element so that it can respond to a keypress event.

The .keypress() method attaches an event handler to an HTML element so that it can respond to a keypress event.

The _______method gets the next sibling of the selected element.

The .next() method gets the next sibling of the selected element. e.g. $('.title').next();

The JQuery ______ method shows the selected HTML element by sliding it down

The .slideDown() method shows the selected HTML element by sliding it down

The _______method hides the selected HTML element by sliding it up.

The .slideUp() method hides the selected HTML element by sliding it up.

The .text() method does what?

The .text() method ADDS TEXT to an HTML ELEMENT.

The _____ property is used to check whether or not a window has been closed by the viewer

The CLOSED property is used to check whether or not a window has been closed by the viewer e.g. windowname.closed

The DOM is useful to represent _______ between elements, similar to a _______. e.g.______

The DOM is useful to represent RELATIONSHIPS between elements, similar to a FAMILY TREE. e.g. PARENT-CHILD-SIBLING(brother sister)

The ____ property is an array containing each frame within a frame set

The FRAMES property is an array containing each frame within a frame set

The In special operator returns true if a ______ is in a specified _____

The In special operator returns true if a PROPERTY is in a specified OBJECT eg var trees=["Ash","Oak","Teak"] /*returns true - 0 index exists 0 in trees /*returns false*/ 4 in trees /*returns true - length array PROPERTY length in trees*/ /*returns true*/ PI in Math

The JavaScript widow object serves as the _______ JavaScript object in _____ ________

The JavaScript widow object serves as the GLOBAL JavaScript object in WEB BROWSERS

Explain the following: var main = function() { ..... }

The code starts with a JavaScript function called main(). A function is a set of INSTRUCTIONS that tells the computer to do something.

Explain the following: var main = function() { $('.dropdown-toggle').click(function() { $('.dropdown-menu').toggle(); }); } $(document).ready(main);

The code starts with a JavaScript function called main(): var main = function() {.....} A function is a set of INSTRUCTIONS that tells the computer to do something. The code uses jQuery to run the main() function once the web page has fully loaded: $(document).ready(main);

The document object helps you gather information about the ______ that is being _____ in the browser

The document object helps you gather information about the PAGE that is being VIEWED in the BROWSER. The document object is created by the browser for each new HTML page that is viewed eg document.write(....)

In line 1 the event handler takes event as a ________. 1: $(document).keypress(function(event) { 2: if(event.which === 109) { 3: $('.dropdown-menu').toggle(); 4: } });

The event handler takes event as a parameter.

The ______ object contains more information about an event, such as which mouse button was clicked or which key was pressed

The event object contains more information about an event, such as which mouse button was clicked or which key was pressed

Append the element "Mark" in the following array: var student= [" Matthew","John "];

student [student.length] ="Luke"; Appends to end of array

Explain the following code in HTML: <script src="jquery.min.js"></script> <script src="app.js"></script>

The first script loads in jQuery: <script src="jquery.min.js"></script> The second script loads in app.js. This is where the code for the program lives: <script src="app.js"></script>

The _____ and ______ properties hold values for width and height of the area of the window in view

The innerWidth and innerHeight properties hold values for width and height of the area of the window in view

Explain the following code: var main = function() {.......}; $(document).ready(main);

The main function is where we'll write our program. The $(document).ready runs the main function as soon as the HTML document has loaded in the browser.

The navigator object gives you access to various properties of the ______ _______

The navigator object gives you access to various properties of the VIEWERS BROWSER eg name version number etc. The navigator object is a PREDEFINED JavaScript object

var n1 =4, n2="2"; var sum=n1+ (+n2); window.alert(sum); What's the output?

The output is 6 (+n2) COERCES the string "2" into a number and then gets added to n1. You could also have used the statement var sum=n1+ +n2;

var fruits = ["Banana","Orange", "Apple","Mango"]; var energy = fruits.join(); What's the output?

The result of energy will be: Banana,Orange,Apple,Mango

The _____ element tells the browser where to find a JavaScript file. Give code example

The script element tells the browser where to find a JavaScript file. Example: ............ <script src="jquery.min.js"></script> <script src="app.js"></script> ...........

Explain function declaration hoisting

This is where a function is CALLED BEFORE it has been DECLARED eg walk(); function walk (){ } JavaScript INTERPRETER looks AHEAD at all variables and functions. If a variable or function was NOT DECLARED at all and it's called then there'll be errors

What is the output from the following code: Staff.prototype. company= "MacDonald's"; var employee2=new Staff("Mark", 35000, 6); var employee2=new Staff("John", 45000, 8); employee1.company=" Sony"; window.alert(employee1. hasOwnProperty("company"); window.alert(employee2. hasOwnProperty("company");

This week output true employee1 has a company "Sony" window.alert(employee1. hasOwnProperty("company"); //this will output false window.alert(employee2. hasOwnProperty("company");

To include JavaScript files in HTML, we use the ______ element.

To include JavaScript files in HTML, we use the script element. E.g. <!doctype html> <html> <head> <link href="style.css" rel="stylesheet"> </head> <body> HERE<script src="jquery.min.js"></script> HERE<script src="app.js"></script> </body> </html>

JavaScript does NOT require numbers to be declared as integers, floating point etc. True or False

True

This code will not compile. True or False? var main = new function() { }; $(document).ready(main);

True. It should be: var main = function() { }; $(document).ready(main);

The following will give errors: var score1 = 1; var score2 = 2; var result = score1/score2

True: ; missing on last line

if (4==="4") {window.alert(true);} This will not print true? True or false

True: STRICT equals === returns true only when the VALUES are of the SAME TYPE and EQUAL

The properties of the navigator object cannot be changed. True or false

True: They are READ ONLY

The following will not give an error. True or false: var alpha =["a","c","b","c"]; var s1=alpha.indexOf("c"); if(!alpha.indexOf("c")){window.alert("found array");}

True: if(!alpha.indexOf("c")){....} Equates to if (!-1){....} !-1 ! Operator is used to compare two items. Should be written as: if(alpha.indexOf("c")===-1) window.alert("found array");}

var constant; will not give a compile error

True: it is a valid variable name. const is a keyword and not a valid variable name

The following will give compile error: var one='hello"; var two="world "; True or false

True: matching pairs must be the same i.e. ' ' and/or " "

var fruits = [2,3,1,20]; fruits.sort(); Will output: 1, 2, 20,3 True or false

True: sort() compared values in a array to STRINGS therefore output 1, 2, 20, 3. Use COMPARISON function as a parameter to sort() in order to correctly sort numbers in array

lastIndexOf([string]) searches an array from back to front and indexOf([string]) searches an array from front to back. True or false

True: these methods provide a way to search for items stored within an array

var volatile; will give a compile error. True or false

True: volatile is a reserved JavaScript keyword

You don't need to specify the data type elements that an array will store. True or false

True: you can use values of ANY TYPE in ANY POSITION within an array. You DON'T need to SPECIFY the NUMBER of ELEMENTS within s an array

change element at index 1 to be "Mark"in the following array: var student= [" Matthew","John "];

student[1]="Mark";

Use _______ to prepend it to the <ul class="posts">..</ul> element. var post = $('.status-box').val(); $('<li>').text(post);

Use .prependTo('.posts') to prepend it to the <ul class="posts">..</ul> element. var post = $('.status-box').val(); $('<li>').text(post).prependTo('.posts');

Use the Delete special operator to delete an _____ or_____ or element in an array

Use the Delete special operator to delete an OBJECT or a PROPERTY or ELEMENT in an array

User interactions with a web page are called ______.

User interactions with a web page are called events.

There are methods of the document object that allow you to create various elements or nodes on a page using JavaScript. Name three of them

Using DOM Nodes: createElement() createAttribute() createTextNode()

Explain line 2: 1 $('.social li').click(function() { 2 $(this).toggleClass('active'); 3 });

We use $(this) to refer to the HTML element that was clicked on. We can now operate on this element using .toggleClass(). $(this).toggleClass('active'); turns on the button

What is function declaration hoisting?

Where a JavaScript FUNCTION can be called ANYWHERE in JavaScript. Firstly JavaScript INTERPRETER will RUN through JavaScript CODE LOOKING for FUNCTIONS

What is the output: var sum=4+1+"th Avenue"; window.alert(sum);

Will display: 5th Avenue

What will be the output after the following code is executed: function pass_grades(item_value, item_index, arr_name) {return ( item_value>=70);} var grades=[74,65,71]; var result=grades.map(pass_grades); window.alert(result);

Will output [true, false, true]

What will be the output after the following code is executed: function pass_grades(item_value, item_index, arr_name) {return ( item_value>=70);} var grades=[74,65,71]; var result=grades.filter(pass_grades); window.alert(result);

Will return ALL of the grades in the array that are GREATER than 70 ie [75,71]

Is there anything wrong with the following code? var b1= document.getElementById("btn1"); b1.addEventListener(onlick, function(event) { alert("The "+window.event.type +" event started this!");} false);

Yes. It should be "click" and not onlick.

Is there anything wrong with the following code? var b1= document.getElementById("btn1"); b1.addEvent("click", function(event) { alert("The "+window.event.type +" event started this!");} false);

Yes. It should be onlick and not "click".

You can place script between ____ tags and______tags only

You can place script between <head> tags and <body>tags

Explain variable declaration hoisting

You can use a variable BEFORE it is declared eg x=5: window.alert(x); var x;

Use JavaScript to write the heading Hello World

document. write("<h1> Hello World</h1>"); Prints: Hello World to webpage

Create a web link using JavaScript for site: www.cit.ie

document. write("<p> <a href="www.cit.ie"> CIT link</a> </p>"); Prints: "CIT link " to webpage

Update the cookie for containing the following "news1= BBC.co.uk" news2= RT.com" "jobs= monster.com"

document.cookie = news1= BBC.co.uk"; document.cookie = news2= RT.com"; document.cookie = "jobs= monster.com"; Cookies are DATA stored in small TEXT FILES on your computer. When a web server has sent a web page to a browser the connection is shut down and the server forgets everything about the user. Cookies were invented to solve the problem "how to REMEMBER INFORMATION about the USER". Note that you can only SET/UPDATE a SINGLE cookie at a time using this method. Cookie string is made up of key/value pairs eg "news1=BBC.co.uk" where key is news1 and value is BBC.co.uk

You have the following HTML code: <body><div id="company"><div id="employee1">Mark</div> <div id="employee2">Sheila</div></div> write the separate ways to access the outer "employee 1"

document.getElementById("company").firstChild; document.getElementById("employee1"); document.getElementById("employee2").previousSibling;

You have the following HTML code: <body><div id="company"><div id="employee1">Mark</div> <div id="employee2">Sheila</div></div> write the separate ways to access the outer "company"

document.getElementById("company"); document.getElementById("employee1"). parentNode; document.getElementById("employee2"). parentNode;

Write code to print when a webpage was last modified

document.write("Last updated"+document.lastModified);

Get the full name of the user browser and print it to the webpage

document.write(navigator.appName) will print eg Microsoft Internet Explorer

Explain line 2-4: 1: $(document).keypress(function(event) { 2: if(event.which === 109) { 3: $('.dropdown-menu').toggle(); 4: } 5: });

event which contains which key was pressed. Keyboard keys are identified by KEY CODES. The m key is identified by the key code 109. Therefore, if the m key is pressed, the dropdown menu is toggled.

what's the method called to get the key called of the key that was pressed by the user

event.keyCode e.g. if(event.keyCode === 80){alert("P Key was pressed");

Use a loop to write "You won the jackpot!" On an new line of a webpage 5 times

for (count=0; count<4; count++){ document.write("You won the jackpot!<br>);}

Write code to display on a webpage the elements of the following array: var students= ["Sam ","Mark"];

for (var k=0; k<students. length;k++){ document.write(students [k]+"<br>);}

Create an object called Staff (using constructor function) with property name salary grade and description where description refers to a function that prints to a web page staff information

function Staff(aName, aSalary, aGrade){this.name= aName; this.salary= aSalary; this.grade= aGrade; this.description= function (){document.write("Experience in Java C objects etc");};}

#1 Create an object called Staff with properties name salary and grade using a function constructor. #2 Create var called curStaff that references an instance of Staff (name= "Mark" salary=30000 grade=6) #3 Create var called curSalary that stores the current salary of curStaff.

function Staff(aName, aSalary, aGrade){this.name= aName; this.salary= aSalary; this.grade= aGrade;} var curStaff=new Staff("Mark", 30000, 6); var curSalary=curStaff.grade; this keyword refers to the CURRENT INSTANCE of Staff object who's values contain "Mark", 30000, 6.

Write code to test if Java is enabled in browser. If it is print to webpage "Java Enabled" if not print to alert window "Java not Enabled"

if (navigator.java Enabled()){ document.write("Java Enabled");} else {window. alert("Java not Enabled");}

jQuery is a collection of _______ _________code that lets us easily create interactive _______on our site

jQuery is a collection of PREWRITTEN JAVASCRIPT code that lets us easily create interactive EFFECTS on our site

var alpha =["a","b","c","d"]; var s1=alpha. splice(2,1); var s2=alpha. splice(2,2); What's the output of s1 and s2

s1 stores a b d (starting at index 2 then remove 1 element ie remove c s2 stores a b ( starting at index 2 then remove 2 elements ie c d

What will s1 contain after the below code is executed? var alpha =["a","c","b","c"]; var s1=alpha.indexOf("c",2);

s1 will be 3: alpha.indexOf("c",2); will start searching for item "c" AT INDEX 2 and continue from there var alpha =["a","c","b","c"];

var alpha =["a","c","b","c"]; var s1=alpha.indexOf("c"); var s2=alpha. LastIndexOf("c"); var s3=alpha.indexOf("d"); what values do s1 s2 and s3 contain after the above gets executed

s1=1 s2=3 and s3=-1 s3 is-1 because the item d is not stored in the array

What will s2 contain after the below code is executed? var s1 =["2",5,22,3]; var s2=alpha.indexOf(2);

s2=-1 As the first item "2" is a string and WILL NOT MATCH the numeric value 2. Therefore returns -1. var s1 =["2",5,22,3]; var s2=alpha.indexOf(2);

var employee1= new Staff ("Mark",35000,6); using a for-in loop extract all properties from Staff instance and print to webpage

var employee1= new Staff ("Mark",35000,6); for ( var prop_name in employee1){document.write( prop_name+" "+ employee1[prop_name]+"<br>"); the venue of each property of the employee1 instance is written on the page

Create an array called friends and initialise them with the following values: Trevor, Ann, Charles, Tamzyn

var friends =new Array("Trevor","Ann","Charles","Tamzyn");

var fruits = ["Banana","Orange", "Apple","Mango"]; Sort the above in alphabetical order

var fruits = ["Banana","Orange", "Apple","Mango"]; fruits.sort(); The result of fruits will be: Apple,Banana,Mango,Orange

Reverse the following array elements: var fruits = ["Banana","Orange", "Apple"];

var fruits = ["Banana","Orange", "Apple"]; fruits.reverse(); The result of fruits will be: Apple,Orange,Banana

var hege = ["Cecilie","Lone"]; var stale = ["Emil","Tobias", "Linus"]; join the two advice arrays together

var hege = ["Cecilie","Lone"]; var stale = ["Emil","Tobias", "Linus"]; var children = hege.concat(stale); The values of the children array will be: Cecilie,Lone,Emil,Tobias,Linus

Using the array below - print all CS modules to a webpage: var students= [["Mark",70,"CS2000"],["Sarah",72,CS2100]];

var i=0, j=0; for(i=0;i<students.length; i++){ for(j=0;j<students[i].length; j++){document.write(student[i][2]+"<br>");}} In the code students[i].length; gets the length of the inner array. student[i][2] contains the CS module for each student and document.write(student[i][2]+"<br>") prints the module to the web page each on a new line.

I wish to hide the highlighted list element by clicking on btn Hide. Write JScript for this [Hide]<- Hide 'btn' element [Item 1: Food]<-currently highlighted by 'read' element)

var main = function () { $(".btn").click(function () { $(".read").hide(); }); };

Use jQuery to select the body HTML element, animate it, and move it left 285px over 200 milliseconds. in Following: var main = function() { $('.icon-menu').click(function() { $('.menu').animate({left: "0px"}, 200); ---CODE HERE-- }); }; $(document).ready(main);

var main = function() { $('.icon-menu').click(function() { $('.menu').animate({left: "0px"}, 200); $('body').animate({left: "285px"}, 200); }); }; $(document).ready(main);

Use jQuery to select the '.icon-close' element. Add the .click() method. 2: use .animate() to change the left offset of the menu to -285px, and the (3:) left offset of the body to 0px. Both are done over 200 milliseconds.

var main = function() { 1-> $('.icon-close').click(function() { 2-> $('.menu').animate({left: "-285px"}, 200); 3-> $('body').animate({left: "0px"}, 200); }); };

1: Add a function inside the .click() method and select the 'menu' class and animate it. 2: move it 0px to the left and make this happen over 200 milliseconds.

var main = function() { 1: -> $('.icon-menu').click(function() { 2:-> $('.menu').animate({left: "0px"}, 200); }); };

1: Inside the app.js file, use the keyword var and create a function called main. 2: Leave the function's code block empty 3: Use jQuery to run the main function once the web page has fully loaded.

var main = function() { } $(document).ready(main);

<div id="div1" title="all about me">this is about me</div> get the title of the above div element

var me_div=document.getElementById( "div1"); window. alert(me_div.title); prints "all about me"

Write the code to create an empty array called myList

var myList= new Array(); Creates an empty array

Write code that prompt user for their name and prints to page. Hint: Use window.prompt()

var name= window. prompt(""Enter name: ", " "); if ((name=== null) || (name===" ")){document. write("Hello Stranger");} else { document. write("Hello "+name);}

<nav id="sLinks"> <a href ="page1. html>Page 1</a> <a href ="page2. html>Page 2</a></nav>Print the total number of web links to an alert window

var nav_element =document. getElementById("sLinks"); var nav_array= nav_element. getElementsByTagName("a"); window.alert( nav_array.length);

Obtain all the elements with a class name nav_pane and store it in a var named nav_pane_elements

var nav_pane_elements= document. getElementsByClass Name ( "nav_pane");

Using switch block - Write JavaScript code: if number is 1 alert it's 1. if number 2 alert it's 2. Otherwise alert not 1 or 2

var num= 2; switch(num){ case 1: window.alert("Yes 1"); break; case 2: window.alert("Yes 2"); break; default: window.alert("Not 1 or 2"); }

Using (condition)?: check if value is 1 and output "Yes" it "No". Store result in var outcome

var num=1; var outcome= (num===1)?"yes":"No";

Write JavaScript code: if number is 1 alert it's 1. if number 2 alert it's 2. Otherwise alert not 1 or 2

var num=3; if (num===1){ window.alert("Yes 1"); } else if( num===2){ window.alert("Yes 2"); } else { window.alert("Not 1 or 2"); }

Declare an empty object or i.e a var that doesn't point to nothing

var object1= null;

Use single var statement to declare multiple variables

var one, two, three;

Use single var standby to declare and initialise multiple var

var one=1, two = 2, three =3;

Declare a variable that is initialised to true. eg var open=...

var open=true;

Declare a variable path that contains "c:\home\mab\sc" and prints the same to the screen

var path="c:\\home\\mab\\sc"; will print "c:\home\mab\src to screen

Declare a variable pets that contains "dog cat bird" and has a tab between each word

var pets="dog\tcat\tbird";

Get the value of the status box and place it in a variable called post

var post = $('.status-box').val();

Write code using reduce method to sum the following array: var s1= [2,4,4];

var s1= [2,4,4]; function sum_nums(prev_value, next_value){return prev_value+ next_value;} var sumTotal = s1.reduce(sum_nums); On first iteration sum_nums() 2+4=6 on second iteration 6+4= 10 sumTotal =10 The above can be ACHIEVED using FOR LOOP: var sumTotal; for(var i=0; i<s1.length; i++){ sumTotal = sumTotal+s1[i];}

Create two variables continaining values 1 and two and divide them.

var score1 = 1; var score2 = 2; var result = score1/score2;

Create an object called staff and add a property called salary with the value 30000

var staff=new Object(); staff.salary=30000; Staff object created a along with a salary PROPERTY initialised with a value 30000. You can create MULTIPLE properties for an object

Create a new property which prints the salary value in an alert window for the following object: var staff=new Object(); staff.salary=30000;

var staff=new Object(); staff.salary=30000; staff.getSalary =function(){window.alert("Salary: "+ staff.salary); /*The following code prints the salary to an alert window*/staff. getSalary();

Create an object (using object literal) called staff and add a property called salary with the value 30000 then add a function called getSalary which prints the salary property to an alert window

var staff={ salary: 30000, getSalary: function(){window.alert("Salary: "+staff.salary);} }; To use (call) the above getSalary function in your code you type: staff.getsalary();

Complete the following code to retrieve the salary of staff object and print it to the webpage: var staff={salary: 30000, grade: "Six"}; var attribute="_____"; function getStaffData(_____) {document.write(_____);} getStaffData(____);

var staff={salary: 30000, grade: "Six"}; var attribute="salary"; function getStaffData(anAttribute) {document.write(staff.attribute);} getStaffData(attribute); getStaffData() is a GENERAL FUNCTION that can retrieve ANY PROPERTY(attribute) FROM an OBJECT based on the PROPERTY NAME being passed as a PARAMETER to the function. This method essentially replaces the need to write separate getter functions to for each object property. In this case 30000 is written to a webpage

var staff={salary: 30000}; Print the salary to a web page using bracket notation

var staff={salary: 30000}; document.print(staff["salary"]);

Create an array called students that will hold 4 student elements

var students = new Array(4);

Create a nested array comprised of students with attributes Mark 70 CS2000 Sarah 72 CS2100

var students= [["Mark",70,"CS2000"],["Sarah",72,CS2100]]; Alternatively you can do this with the array CONSTRUCTOR to create an OBJECT array: var students= new array (new array ("Mark",70,"CS2000"), new array("Sarah",72,CS2100));

Set Sum equal to 15 and 12

var sum = 15+12;

1: Write a function called sum that takes in two values, adds them and returns the result. 2: Call the function sum with two values 1 and 2 3: store it in another var result

var sum= function(num1, num2) { var result = num1+num2; return result; }; var result = sum(1,2);

<div id="mark_text" >Hello World</div> store the above info based on its id

var textElement = document. getElementById(" mark_text");

Find the length of the string: var tweet = "Hiking trip on Saturday";

var tweet = "Hiking trip on Saturday"; tweet.length;

Using addEventListener() - when the user clicks a button (btn1)- an alert appears stating "Link Clicked"

var web_page1 ="www.CIT.ie"; var b1 = document.getElementById("btn1"); b1.addEventListener("click", function() {window.alert('Link Clicked');}, false);

Write a function expression called write

var write=function (){..}; It's DECLARED like an ANONYMOUS function. Used once off

Create a JavaScript alert to display "Warning!"

window.alert ("Warning! ");

Write code to an alert that prints the info about the last webpage the user visited before laying on the current page

window.alert("you came from "+document.referrer);

Write code to print the number of pages in the session history to an alert window

window.alert(history. length); the history object only has one property that returns the number of pages in the session history

Print to an alert the status of whether a web browser has cookies website or not

window.alert(navigator.cookieEnabled); prints true or false to window alert

What will be the output after the following code is executed: function pass_grades(item_value, item_index, arr_name) {return ( item_value>=70);} var grades=[74,65,71]; var result=grades.every(pass_grades); window.alert(result);

window.alert(result); will output false as EVERY item must be greater than 70. Index 1 contains item 65

Using a with statement write code to print all the properties of the object Staff: function Staff(name, salary, grade) { this.name; this.salary; this.grade;} var employee = new Staff ("Peter ", 38000, 6);

with (employee) {document.write("Name: "+name+"<br>"); document.write("Salary: "+salary with (employee) {document.write("Name: "+name+"<br>"); document.write("Salary: "+salary+"<br>" ); document.write("Grade: "+grade+"<br>" ); }


Conjuntos de estudio relacionados

Davis Edge: Postpartum Physiological Assessments and Nursing Care

View Set

Chapter 8: Establishing a Constructive Climate Test

View Set

Chapter 2: Theory, Research, and Evidence-Informed Practice

View Set

American Government Ch. 13 Practice Test 1

View Set

Module 55. Biomedical Therapies and Preventing Psychological Disorders

View Set

intro to politics/gov quiz questions

View Set