Javascript
Javascript
2. When a user views a page containing a JavaScript program, which machine actually executes the script?
A. The User's machine running a Web browser
B. The Web server
C. A central machine deep within Netscape's corporate offices
D. None of the above
6. _____ JavaScript statements embedded in an HTML page can respond to user events such as mouse-
clicks, form input, and page navigation.
A. Client-side
B. Server-side
C. Local
D. Native
11. ______ tag is an extension to HTML that can enclose any number of JavaScript statements.
A. <SCRIPT>
B. <BODY>
C. <HEAD>
D. <TITLE>
13. Which of the following attribute can hold the JavaScript version?
A. LANGUAGE
B. SCRIPT
C. VERSION
D. None of the above
15. Which of the following way can be used to indicate the LANGUAGE attribute?
A. <LANGUAGE="JavaScriptVersion">
B. <SCRIPT LANGUAGE="JavaScriptVersion">
C. <SCRIPT LANGUAGE="JavaScriptVersion"> JavaScript statements…</SCRIPT>
D. <SCRIPT LANGUAGE="JavaScriptVersion"!> JavaScript statements…</SCRIPT>
16. Inside which HTML element do we put the JavaScript?
A. <js>
B. <scripting>
C. <script>
D. <javascript>
17. What is the correct syntax for referring to an external script called " abc.js"?
A. <script href=" abc.js">
B. <script name=" abc.js">
C. <script src=" abc.js">
D. None of the above
19. Which of the following navigator object properties is the same in both Netscape and IE?
A. navigator.appCodeName
B. navigator.appName
C. navigator.appVersion
D. None of the above
22. If para1 is the DOM object for a paragraph, what is the correct syntax to change the text within the
paragraph?
A. "New Text"?
B. para1.value="New Text";
C. para1.firstChild.nodeValue= "New Text";
D. para1.nodeValue="New Text";
23. JavaScript entities start with _______ and end with _________.
A. Semicolon, colon
B. Semicolon, Ampersand
C. Ampersand, colon
D. Ampersand, semicolon
24. Which of the following best describes JavaScript?
A. a low-level programming language.
B. a scripting language precompiled in the browser.
C. a compiled scripting language.
D. an object-oriented scripting language.
28. ______method evaluates a string of JavaScript code in the context of the specified object.
A. Eval
B. ParseInt
C. ParseFloat
D. Efloat
29. Which of the following event fires when the form element loses the focus: <button>, <input>, <label>,
<select>, <textarea>?
A. onfocus
B. onblur
C. onclick
D. ondblclick
32. Using _______ statement is how you test for a specific condition.
A. Select
B. If
C. Switch
D. For
35. The _______ method of an Array object adds and/or removes elements from an array.
A. Reverse
B. Shift
C. Slice
D. Splice
36. To set up the window to capture all Click events, we use which of the following statement?
A. window.captureEvents(Event.CLICK);
B. window.handleEvents (Event.CLICK);
C. window.routeEvents(Event.CLICK );
D. window.raiseEvents(Event.CLICK );
39. To enable data tainting, the end user sets the _________ environment variable.
A. ENABLE_TAINT
B. MS_ENABLE_TAINT
C. NS_ENABLE_TAINT
D. ENABLE_TAINT_NS
40. In JavaScript, _________ is an object of the target language data type that encloses an object of the
source language.
A. a wrapper
B. a link
C. a cursor
D. a form
41. When a JavaScript object is sent to Java, the runtime engine creates a Java wrapper of type
___________
A. ScriptObject
B. JSObject
C. JavaObject
D. Jobject
42. _______ class provides an interface for invoking JavaScript methods and examining JavaScript
properties.
A. ScriptObject
B. JSObject
C. JavaObject
D. Jobject
43. _________ is a wrapped Java array, accessed from within JavaScript code.
A. JavaArray
B. JavaClass
C. JavaObject
D. JavaPackage
44. A ________ object is a reference to one of the classes in a Java package, such as netscape.javascript .
A. JavaArray
B. JavaClass
C. JavaObject
D. JavaPackage
45. The JavaScript exception is available to the Java code as an instance of __________
A. netscape.javascript.JSObject
B. netscape.javascript.JSException
C. netscape.plugin.JSException
D. None of the above
46. To automatically open the console when a JavaScript error occurs which of the following is added to
prefs.js?
A. user_pref(" javascript.console.open_on_error", false);
B. user_pref("javascript.console.open_error ", true);
C. user_pref("javascript.console.open_error ", false);
D. user_pref("javascript.console.open_on_error", true);
47. To open a dialog box each time an error occurs, which of the following is added to prefs.js?
A. user_pref("javascript.classic.error_alerts", true);
B. user_pref("javascript.classic.error_alerts ", false);
C. user_pref("javascript.console.open_on_error ", true);
D. user_pref("javascript.console.open_on_error ", false);
49. The syntax of capture events method for document object is ______________
A. captureEvents()
B. captureEvents(args eventType)
C. captureEvents(eventType)
D. captureEvents(eventVal)
(Note: the first comment, "<--" hides the content of the script from browsers that
don't understand javascript. The "// -->" finishes the comment. The "//" tells
javascript that this is a comment so javascript doesn't try to interpret the "-->". If
your audience has much older browsers, you should put this comments inside
your javascript. If most of your audience has newer browsers, the comments can
be omitted. For brevity, in most examples here the comments are not shown. )
The above code will look like this on Javascript enabled browsers,
2. Javascript can be placed inside the <head> element
Functions and global variables typically reside inside the <head> element.
<head>
<title>Default Test Page</title>
<script language="JavaScript" type="text/javascript">
var myVar = "";
function timer(){setTimeout('restart()',10);}
document.onload=timer();
</script>
</head>
How can JavaScript make a Web site easier to use? That is, are there certain
JavaScript techniques that make it easier for people to use a Web site?
JavaScript's greatest potential gift to a Web site is that scripts can make the page
more immediately interactive, that is, interactive without having to submit every
little thing to the server for a server program to re-render the page and send it
back to the client. For example, consider a top-level navigation panel that has,
say, six primary image map links into subsections of the Web site. With only a
little bit of scripting, each map area can be instructed to pop up a more detailed
list of links to the contents within a subsection whenever the user rolls the cursor
atop a map area. With the help of that popup list of links, the user with a
scriptable browser can bypass one intermediate menu page. The user without a
scriptable browser (or who has disabled JavaScript) will have to drill down
through a more traditional and time-consuming path to the desired content
How can JavaScript be used to improve the "look and feel" of a Web site? By
the same token, how can JavaScript be used to improve the user interface?
On their own, Web pages tend to be lifeless and flat unless you add animated
images or more bandwidth-intensive content such as Java applets or other
content requiring plug-ins to operate (ShockWave and Flash, for example).
Embedding JavaScript into an HTML page can bring the page to life in any
number of ways. Perhaps the most visible features built into pages recently with
the help of JavaScript are the so-called image rollovers: roll the cursor atop a
graphic image and its appearance changes to a highlighted version as a
feedback mechanism to let you know precisely what you're about to click on. But
there are less visible yet more powerful enhancements to pages that JavaScript
offers.
Interactive forms validation is an extremely useful application of JavaScript. While
a user is entering data into form fields, scripts can examine the validity of the
data--did the user type any letters into a phone number field?, for instance.
Without scripting, the user has to submit the form and let a server program (CGI)
check the field entry and then report back to the user. This is usually done in a
batch mode (the entire form at once), and the extra transactions take a lot of
time and server processing power. Interactive validation scripts can check each
form field immediately after the user has entered the data, while the information
is fresh in the mind.
Another helpful example is embedding small data collections into a document
that scripts can look up without having to do all the server programming for
database access. For instance, a small company could put its entire employee
directory on a page that has its own search facility built into the script. You can
cram a lot of text data into scripts no larger than an average image file, so it's
not like the user has to wait forever for the data to be downloaded.
Other examples abound, such as interactive tree-structure tables of contents.
More modern scriptable browsers can be scripted to pre-cache images during the
page's initial download to make them appear lickety-split when needed for image
swapping. I've even written some multi-screen interactive applications that run
entirely on the client, and never talk to the server once everything is
downloaded.
scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
Now our array scrips has 4 elements inside it and we can print or access them by
using their index number. Note that index number starts from 0. To get the third
element of the array we have to use the index number 2 . Here is the way to get
the third element of an array.
document.write(scripts[2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);
Fixed width tables are rendered by the browser based on the widths of the
columns in the first row, resulting in a faster display in case of large tables. Use
the CSS style table-layout:fixed to specify a fixed width table.
If the table is not specified to be of fixed width, the browser has to wait till all
data is downloaded and then infer the best width for each of the columns. This
process can be very slow for large tables.
...
var re = new RegExp("^(&[A-Za-z_0-9]{1,}=[A-Za-z_0-9]{1,})*$");
var text = myWidget.value;
var OK = re.test(text);
if( ! OK ) {
alert("The extra parameters need some work.\r\n Should be something
like: \"&a=1&c=4\"");
}
cookies.txt
c:\Program Files\Netscape\Users\username\cookies.txt
In the case of IE,each cookie is stored in a separate file namely
[email protected].
c:\Windows\Cookies\[email protected]
How to add Buttons in JavaScript?
The most basic and ancient use of buttons are the "submit" and "clear", which
appear slightly before the Pleistocene period. Notice when the "GO!" button is
pressed it submits itself to itself and appends the name in the URL.
<form action="" name="buttonsGalore" method="get">
Your Name: <input type="text" name="mytext" />
<br />
<input type="submit" value="GO!" />
<input type="reset" value="Clear All" />
</form>
Another useful approach is to set the "type" to "button" and use the "onclick"
event.
<script type="text/javascript">
function displayHero(button) {
alert("Your hero is \""+button.value+"\".");
}
</script>
Are you concerned that older browsers don't support JavaScript and thus
exclude a set of Web users? individual users?
Fragmentation of the installed base of browsers will only get worse. By definition,
it can never improve unless absolutely everyone on the planet threw away their
old browsers and upgraded to the latest gee-whiz versions. But even then, there
are plenty of discrepancies between the scriptability of the latest Netscape
Navigator and Microsoft Internet Explorer.
The situation makes scripting a challenge, especially for newcomers who may not
be aware of the limitations of earlier browsers. A lot of effort in my books and
ancillary material goes toward helping scripters know what features work in
which browsers and how to either workaround limitations in earlier browsers or
raise the compatibility common denominator.
Designing scripts for a Web site requires making some hard decisions about if,
when, and how to implement the advantages scripting offers a page to your
audience. For public Web sites, I recommend using scripting in an additive way:
let sufficient content stand on its own, but let scriptable browser users receive an
enhanced experience, preferably with the same HTML document.
In a pop-up browser window, how do you refer to the main browser window
that opened it?
Use window.opener to refer to the main window from pop-ups.
What and where are the best JavaScript resources on the Web?
The Web has several FAQ areas on JavaScript. The best place to start is
something called the meta-FAQ [14-Jan-2001 Editor's Note: I can't point to it
anymore, it is broken!], which provides a high-level overview of the JavaScript
help available on the Net. As for fact-filled FAQs, I recommend one maintained by
Martin Webb and a mini-FAQ that I maintain.
For interactive help with specific problems, nothing beats the primary JavaScript
Usenet newsgroup, comp.lang.javascript. Depending on my work backlog, I
answer questions posted there from time to time. Netscape and Microsoft also
have vendor-specific developer discussion groups as well as detailed
documentation for the scripting and object model implementations.
What are the problems associated with using JavaScript, and are there
JavaScript techniques that you discourage?
Browser version incompatibility is the biggest problem. It requires knowing how
each scriptable browser version implements its object model. You see, the
incompatibility rarely has to do with the core JavaScript language (although there
have been improvements to the language over time); the bulk of incompatibility
issues have to do with the object models that each browser version implements.
For example, scripters who started out with Navigator 3 implemented the image
rollover because it looked cool. But they were dismayed to find out that the
image object wasn't scriptable in Internet Explorer 3 or Navigator 2. While there
are easy workarounds to make this feature work on newer browsers without
disturbing older ones, it was a painful learning experience for many.
The second biggest can of worms is scripting connections between multiple
windows. A lot of scripters like to have little windows pop up with navigation bars
or some such gizmos. But the object models, especially in the older browser
versions, don't make it easy to work with these windows the minute you put a
user in front of them--users who can manually close windows or change their
stacking order. More recently, a glitch in some uninstall routines for Windows 95
applications can disturb vital parts of the system Registry that Internet Explorer 4
requires for managing multiple windows. A scripter can't work around this
problem, because it's not possible to detect the problem in a user's machine. I
tend to avoid multiple windows that interact with each other. I think a lot of
inexperienced Web surfers can also get confused by them.
How to access an external javascript file that is stored externally and not
embedded?
This can be achieved by using the following tag between head tags or between
body tags.
<script src="abc.js"></script>How to access an external javascript file that is
stored externally and not embedded? where abc.js is the external javscript file to
be accessed.
What Web sites do you feel use JavaScript most effectively (i.e., best-in-
class examples)? The worst?
The best sites are the ones that use JavaScript so transparently, that I'm not
aware that there is any scripting on the page. The worst sites are those that try
to impress me with how much scripting is on the page.
How to hide javascript code from old browsers that dont run it?
Use the below specified style of comments <script language=javascript> <!--
javascript code goes here // --> or Use the <NOSCRIPT>some html code
</NOSCRIPT> tags and code the display html statements between these and this
will appear on the page if the browser does not support javascript
How to comment javascript code?
Use // for line comments and
/*
What does the term sticky session mean in a web-farm scenario? Why
would you use a sticky session? What is the potential disadvantage of using
a sticky session?
Sticky session refers to the feature of many commercial load balancing solutions
for web-farms to route the requests for a particular session to the same physical
machine that serviced the first request for that session. This is mainly used to
ensure that a in-proc session is not lost as a result of requests for a session being
routed to different servers. Since requests for a user are always routed to the
same machine that first served the request for that session, sticky sessions can
cause uneven load distribution across servers.
You have an ASP.NET web application running on a web-farm that does not
use sticky sessions - so the requests for a session are not guaranteed to be
served the same machine. Occasionally, the users get error message
Validation of viewstate MAC failed. What could be one reason that is causing
this error?
The most common reason for this error is that the machinekey value in
machine.config is different for each server. As a result, viewstate encoded by one
machine cannot be decoded by another. To rectify this, edit the machine.config
file on each server in the web-farm to have the same value for machinekey.
...
How to find the selected radio button immediately using the 'this' variable?
<script>
function favAnimal(button) {
alert('You like '+button.value+'s.');
}
</script>
<input type="radio" name="marsupial" value="kangaroo"
onchange="favAnimal(this)">Kangaroo
<br /><input type="radio" name="marsupial" value="Opossum"
onchange="favAnimal(this)">Opossum
<br /><input type="radio" name="marsupial" value="Tasmanian Tiger"
onchange="favAnimal(this)">Tasmanian Tiger
<p id="firstP">firstP<p>
</body>
</html>
How to have the status line update when the mouse goes over a link (The
support of the status line is sporadic)?
<a href="javascript.shtml"
onmouseover="window.status='Hi There!';return true"
onmouseout="window.status='';return true">Look at the Status bar</a>
Look at the Status bar as your cursor goes over the link.
You can also use the W3C addEvventListener() method, but it does not work in IE
yet:
Key Events
<script type="text/javascript">
function setStatus(name,evt) {
evt = (evt) ? evt : ((event) ? event : null); /* ie or standard? */
var charCode = evt.charCode;
var status = document.getElementById("keyteststatus");
var text = name +": "+evt.keyCode;
status.innerHTML = text;
status.textContent = text;
}
</script>
<form action="">
<input type="text" name="keytest" size="1" value=""
onkeyup="setStatus('keyup',event)"
onkeydown="setStatus('keydown',event)"
/>
<p id="keyteststatus">status</p>
</form>
if ( x == y) {
myElement.style.visibility = 'visible';
} else {
myElement.style.visibility = 'hidden';
}
This produces
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday"];
<script type="text/javascript">
var days = ["Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday"];
document.write("days:"+days.join(","));
</script>
This produces
days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
<script type="text/javascript">
var numbers = ["one", "two", "three", "four"];
numbers.push("five");
numbers.push("six");
document.write(numbers.pop());
document.write(numbers.pop());
document.write(numbers.pop());
</script>
This produces
sixfivefour
<script type="text/javascript">
var myMovie = new Object();
myMovie.title = "Aliens";
myMovie.director = "James Cameron";
document.write("movie: title is \""+myMovie.title+"\"");
<
This produces
movie: title is "Aliens"
To create an object you write a method with the name of your object and invoke
the method with "new".
<script type="text/javascript">
function movie(title, director) {
this.title = title;
this.director = director;
}
var aliens = new movie("Aliens","Cameron");
document.write("aliens:"+aliens.toString());
</script>
This produces
aliens:[object Object]
You can also use an abbreviated format for creating fields using a ":" to separate
the name of the field from its value. This is equivalent to the above code using
"this.".
<script type="text/javascript">
function movie(title, director) {
title : title;
director : director;
}
var aliens = new movie("Aliens","Cameron");
document.write("aliens:"+aliens.toString());
</script>
This produces
aliens:[object Object]
<script type="text/javascript">
function movie(title, director) {
this.title = title;
this.director = director;
this.toString = function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
}
var narnia = new movie("Narni","Andrew Adamson");
document.write(narnia.toString());
</script>
This produces
title: Narni director: Andrew Adamson
Or we can use a previously defined function and assign it to a variable. Note that
the name of the function is not followed by parenthesis, otherwise it would just
execute the function and stuff the returned value into the variable.
<script type="text/javascript">
function movieToString() {
return("title: "+this.title+" director: "+this.director);
}
function movie(title, director) {
this.title = title;
this.director = director;
this.toString = movieToString; //assign function to this method pointer
}
var aliens = new movie("Aliens","Cameron");
document.write(aliens.toString());
</script>
This produces
title: Aliens director: Cameron
eval()?
The eval() method is incredibly powerful allowing you to execute snippets of code
during execution.
<script type="text/javascript">
var USA_Texas_Austin = "521,289";
document.write("Population is "+eval("USA_"+"Texas_"+"Austin"));
</script>
This produces
Population is 521,289
unescape(), escape()
These are similar to the decodeURI() and encodeURI(), but escape() is used for
only portions of a URI.
<script type="text/javascript">
var myvalue = "Sir Walter Scott";
document.write("Original myvalue: "+myvalue);
document.write("<br />escaped: "+escape(myvalue));
document.write("<br />uri part: \"&author="+escape(myvalue)+"\"");
</script>
If you use escape() for the whole URI... well bad things happen.
<script type="text/javascript">
var uri = "http://www.google.com/search?q=sonofusion Taleyarkhan"
document.write("Original uri: "+uri);
document.write("
escaped: "+escape(uri));
v/script>
decodeURI(), encodeURI()
Many characters cannot be sent in a URL, but must be converted to their hex
encoding. These functions are used to convert an entire URI (a superset of URL)
to and from a format that can be sent via a URI.
<script type="text/javascript">
var uri = "http://www.google.com/search?q=sonofusion Taleyarkhan"
document.write("Original uri: "+uri);
document.write("<br />encoded: "+encodeURI(uri));
</script>
Undefined variables are those that are not assigned any value but are declared in the
program.Trying to read such variables gives special value called undefined value.