Sie sind auf Seite 1von 88

1

HTML & JavaScript interview questions


Set 1:
What is HTML?
Answer1: HTML, or HyperText Markup Language, is a Universal language which allows an individual using special code to create web pages to be viewed on the Internet. Answer2: HTML ( H yper T ext M arkup L anguage) is the language used to write Web pages. You are looking at a Web page right now. You can view HTML pages in two ways: * One view is their appearance on a Web browser, just like this page -- colors, different text sizes, graphics. * The other view is called "HTML Code" -- this is the code that tells the browser what to do.
What is a tag? In HTML, a tag tells the browser what to do. When you write an HTML page, you enter tags for many reasons -- to change the appearance of text, to show a graphic, or to make a link to another page. What is the simplest HTML page? HTML Code: <HTML> <HEAD> <TITLE>This is my page title! </TITLE> </HEAD> <BODY> This is my message to the world! </BODY> </HTML>

Browser Display: This is my message to the world!


How do I create frames? What is a frameset? Frames allow an author to divide a browser window into multiple (rectangular) regions. Multiple documents can be displayed in a single window, each within its own frame. Graphical browsers allow these frames to be scrolled independently of each other, and links can update the document displayed in one frame without affecting the others. You can't just "add frames" to an existing document. Rather, you must create a frameset document that defines a particular combination of frames, and then display your content documents inside those frames. The frameset document should also include alternative non-framed content in a NOFRAMES element. The HTML 4 frames model has significant design flaws that cause usability problems for web users. Frames should be used only with great care. How can I include comments in HTML? Technically, since HTML is an SGML application, HTML uses SGML comment syntax.

2
However, the full syntax is complex, and browsers don't support it in its entirety anyway. Therefore, use the following simplified rule to create HTML comments that both have valid syntax and work in browsers: An HTML comment begins with "<!--", ends with "-->", and does not contain "--" or ">" anywhere in the comment. The following are examples of HTML comments: * <!-- This is a comment. --> * <!-- This is another comment, and it continues onto a second line. --> * <!----> Do not put comments inside tags (i.e., between "<" and ">") in HTML markup.
What is a Hypertext link? A hypertext link is a special tag that links one page to another page or resource. If you click the link, the browser jumps to the link's destination. How comfortable are you with writing HTML entirely by hand?

Very. I dont usually use WYSIWYG. The only occasions when I do use Dreamweaver are when I want to draw something to see what it looks like, and then Ill usually either take that design and hand-modify it or build it all over again from scratch in code. I have actually written my own desktop HTML IDE for Windows (its called Less Than Slash) with the intention of deploying it for use in web development training. If has built-in reference features, and will autocomplete code by parsing the DTD you specify in the file. That is to say, the program doesnt know anything about HTML until after it parses the HTML DTD you specified. This should give you some idea of my skill level with HTML.
What is everyone using to write HTML? Everyone has a different preference for which tool works best for them. Keep in mind that typically the less HTML the tool requires you to know, the worse the output of the HTML. In other words, you can always do it better by hand if you take the time to learn a little HTML. What is a DOCTYPE? Which one do I use? According to HTML standards, each HTML document begins with a DOCTYPE declaration that specifies which version of HTML the document uses. Originally, the DOCTYPE declaration was used only by SGML-based tools like HTML validators, which needed to determine which version of HTML a document used (or claimed to use). Today, many browsers use the document's DOCTYPE declaration to determine whether to use a stricter, more standards-oriented layout mode, or to use a "quirks" layout mode that attempts to emulate older, buggy browsers. Can I nest tables within tables? Yes, a table can be embedded inside a cell in another table. Here's a simple example:

<table>

3
<tr> <td>this is the first cell of the outer table</td> <td>this is the second cell of the outer table, with the inner table embedded in it <table> <tr> <td>this is the first cell of the inner table</td> <td>this is the second cell of the inner table</td> </tr> </table> </td> </tr> </table> The main caveat about nested tables is that older versions of Netscape Navigator have problems with them if you don't explicitly close your TR, TD, and TH elements. To avoid problems, include every </tr>, </td>, and </th> tag, even though the HTML specifications don't require them. Also, older versions of Netscape Navigator have problems with tables that are nested extremely deeply (e.g., tables nested ten deep). To avoid problems, avoid nesting tables more than a few deep. You may be able to use the ROWSPAN and COLSPAN attributes to minimize table nesting. Finally, be especially sure to validate your markup whenever you use nested tables.

How do I align a table to the right (or left)?


You can use <TABLE ALIGN="right"> to float a table to the right. (Use ALIGN="left" to float it to the left.) Any content that follows the closing </TABLE> tag will flow around the table. Use <BR CLEAR="right"> or <BR CLEAR="all"> to mark the end of the text that is to flow around the table, as shown in this example: The table in this example will float to the right. <table align="right">...</table> This text will wrap to fill the available space to the left of (and if the text is long enough, below) the table. <br clear="right"> This text will appear below the table, even if there is additional room to its left.
How can I use tables to structure forms? Small forms are sometimes placed within a TD element within a table. This can be a useful for positioning a form relative to other content, but it doesn't help position the form-related elements relative to each other. To position form-related elements relative to each other, the entire table must be within the form. You cannot start a form in one TH or TD element and end in another. You cannot place the form within the table without placing it inside a TH or TD element. You can put the table inside the form, and then use the table to position the INPUT, TEXTAREA, SELECT, and other form-related elements, as shown in the following example.

<FORM ACTION="[URL]"> <TABLE BORDER="0"> <TR> <TH>Account:</TH> <TD><INPUT TYPE="text" NAME="account"></TD>

4
</TR> <TR> <TH>Password:</TH> <TD><INPUT TYPE="password" NAME="password"></TD> </TR> <TR> <TD> </TD> <TD><INPUT TYPE="submit" NAME="Log On"></TD> </TR> </TABLE> </FORM>
How do I center a table? In your HTML, use

<div class="center"> <table>...</table> </div> In your CSS, use div.center { text-align: center;

}
div.center table { margin-left: auto; margin-right: auto; text-align: left;

}
How do I use forms? The basic syntax for a form is: <FORM ACTION="[URL]">...</FORM> When the form is submitted, the form data is sent to the URL specified in the ACTION attribute. This URL should refer to a server-side (e.g., CGI) program that will process the form data. The form itself should contain

* at least one submit button (i.e., an <INPUT TYPE="submit" ...> element), * form data elements (e.g., <INPUT>, <TEXTAREA>, and <SELECT>) as needed, and * additional markup (e.g., identifying data elements, presenting instructions) as needed.
How can I check for errors? HTML validators check HTML documents against a formal definition of HTML syntax and then output a list of errors. Validation is important to give the best chance of correctness on unknown browsers (both existing browsers that you haven't seen and future browsers that haven't been written yet). HTML checkers (linters) are also useful. These programs check documents for specific problems, including some caused by invalid markup and others caused by common browser bugs. Checkers may pass some invalid documents, and they may fail some valid ones. All validators are functionally equivalent; while their reporting styles may vary, they will

5
find the same errors given identical input. Different checkers are programmed to look for different problems, so their reports will vary significantly from each other. Also, some programs that are called validators (e.g. the "CSE HTML Validator") are really linters/checkers. They are still useful, but they should not be confused with real HTML validators. When checking a site for errors for the first time, it is often useful to identify common problems that occur repeatedly in your markup. Fix these problems everywhere they occur (with an automated process if possible), and then go back to identify and fix the remaining problems. Link checkers follow all the links on a site and report which ones are no longer functioning. CSS checkers report problems with CSS style sheets.
Do I have to memorize a bunch of tags? No. Most programs that help you write HTML code already know most tags, and create them when you press a button. But you should understand what a tag is, and how it works. That way you can correct errors in your page more easily. How do I make a form so it can be submitted by hitting ENTER?

The short answer is that the form should just have one <INPUT TYPE=TEXT> and no TEXTAREA, though it can have other form elements like checkboxes and radio buttons.
How do I set the focus to the first form field? You cannot do this with HTML. However, you can include a script after the form that sets the focus to the appropriate field, like this:

<form id="myform" name="myform" action=...> <input type="text" id="myinput" name="myinput" ...> </form> <script type="text/javascript"> document.myform.myinput.focus(); </script> A similar approach uses <body onload=...> to set the focus, but some browsers seem to process the ONLOAD event before the entire document (i.e., the part with the form) has been loaded.
How can I eliminate the extra space after a </form> tag? HTML has no mechanism to control this. However, with CSS, you can set the marginbottom of the form to 0. For example: <form style="margin-bottom:0;" action=...>

You can also use a CSS style sheet to affect all the forms on a page: form { margin-bottom: 0 ; }
How can I use tables to structure forms? Small forms are sometimes placed within a TD element within a table. This can be a useful for positioning a form relative to other content, but it doesn't help position the form-related

6
elements relative to each other. To position form-related elements relative to each other, the entire table must be within the form. You cannot start a form in one TH or TD element and end in another. You cannot place the form within the table without placing it inside a TH or TD element. You can put the table inside the form, and then use the table to position the INPUT, TEXTAREA, SELECT, and other form-related elements, as shown in the following example. <form action="[URL]"> <table border="0"> <tr> <th scope="row"> <label for="account">Account:</label> </th> <td> <input type="text" name="account" id="account"> </td> </tr> <tr> <th scope="row"> <label for="password">Password: </th> <td> <input type="password" name="password" id="password"> </td> </tr> <tr> <td> </td> <td><input type="submit" name="Log On"></td> </tr> </table> </form>

Can I have two or more actions in the same form?


No. A form must have exactly one action. However, the server-side (e.g., CGI) program that processes your form submissions can perform any number of tasks (e.g., updating a database, sending email, logging a transaction) in response to a single form submission.
How can I use forms for pull-down navigation menus? There is no way to do this in HTML only; something else must process the form. JavaScript processing will work only for readers with JavaScript-enabled browsers. CGI and other server-side processing is reliable for human readers, but search engines have problems following any form-based navigation. How can I avoid using the whole URL? The URL structure defines a hierarchy (or relationship) that is similar to the hierarchy of subdirectories (or folders) in the filesystems used by most computer operating systems. The segments of a URL are separated by slash characters ("/"). When navigating the URL hierarchy, the final segment of the URL (i.e., everything after the final slash) is similar to a file in a filesystem. The other segments of the URL are similar to the subdirectories and folders in a filesystem. A relative URL omits some of the information needed to locate the referenced document. The omitted information is assumed to be the same as for the base document that

7
contains the relative URL. This reduces the length of the URLs needed to refer to related documents, and allows document trees to be accessed via multiple access schemes (e.g., "file", "http", and "ftp") or to be moved without changing any of the embedded URLs in those documents. Before the browser can use a relative URL, it must resolve the relative URL to produce an absolute URL. If the relative URL begins with a double slash (e.g., //www.yoursite.com/faq/html/), then it will inherit only the base URL's scheme. If the relative URL begins with a single slash (e.g., /faq/html/), then it will inherit the base URL's scheme and network location. If the relative URL does not begin with a slash (e.g., all.html , ./all.html or ../html/), then it has a relative path and is resolved as follows. 1. The browser strips everything after the last slash in the base document's URL and appends the relative URL to the result. 2. Each "." segment is deleted (e.g., ./all.html is the same as all.html, and ./ refers to the current "directory" level in the URL hierarchy). 3. Each ".." segment moves up one level in the URL hierarchy; the ".." segment is removed, along with the segment that precedes it (e.g., foo/../all.html is the same as all.html, and ../ refers to the parent "directory" level in the URL hierarchy). Some examples may help make this clear. If the base document is <URL:http://www.yoursite.com/faq/html/basics.html>, then all.html and ./all.html refer to <URL:http://www.yoursite.com/faq/html/all.html> ./ refers to <URL:http://www.yoursite.com/faq/html/> ../ refers to <URL:http://www.yoursite.com/faq/> ../cgifaq.html refers to <URL:http://www.yoursite.com/faq/cgifaq.html> ../../reference/ refers to <URL:http://www.yoursite.com/reference/> Please note that the browser resolves relative URLs, not the server. The server sees only the resulting absolute URL. Also, relative URLs navigate the URL hierarchy. The relationship (if any) between the URL hierarchy and the server's filesystem hierarchy is irrelevant.
Can I use percentage values for <TD WIDTH=...>? The HTML 3.2 and HTML 4.0 specifications allow only integer values (representing a number of pixels) for the WIDTH attribute of the TD element. However, the HTML 4.0 DTD allows percentage (and other non-integer) values, so an HTML validator will not complain about <TD WIDTH="xx%">. It should be noted that Netscape and Microsoft's browsers interpret percentage values for <TD WIDTH=...> differently. However, their interpretations (and those of other table-aware browsers) happen to match when combined with <TABLE WIDTH="100%">. In such situations, percentage values can be used relatively safely, even though they are prohibited by the public specifications.

Why doesn't <TABLE WIDTH="100%"> use the full browser width?


Graphical browsers leave a narrow margin between the edge of the display area and the

8
content. Also note that Navigator always leaves room for a scrollbar on the right, but draws the scrollbar only when the document is long enough to require scrolling. If the document does not require scrolling, then this leaves a right "margin" that cannot be removed.
Why is there extra space before or after my table? This is often caused by invalid HTML syntax. Specifically, it is often caused by loose content within the table (i.e., content that is not inside a TD or TH element). There is no standard way to handle loose content within a table. Some browsers display all loose content before or after the table. When the loose content contains only multiple line breaks or empty paragraphs, then these browsers will display all this empty space before or after the table itself. The solution is to fix the HTML syntax errors. All content within a table must be within a TD or TH element. How do I create a link that sends me email? Use a mailto link, for example How can I have two sets of links with different colors? You can suggest this presentation in a style sheet. First, specify colors for normal links, like this:

a:link {color: blue; background: white} a:visited {color: purple; background: white} a:active {color: red; background: white} Next, identify the links that you want to have different colors. You can use the CLASS attribute in your HTML, like this: <a class="example1" href="[URL]">[link text]</a> Then, in your style sheet, use a selector for links with this CLASS attribute, like this: a.example1:link {color: yellow; background: black} a.example1:visited {color: white; background: black} a.example1:active {color: red; background: black} Alternatively, you can identify an element that contains the links that you want to have different colors, like this: <div class="example2">... <a href="[URL]">[link text]</a>... <a href="[URL]">[link text]</a>... <a href="[URL]">[link text]</a>... </div> Then, in your style sheet, use a selector for links in this containing element, like this: .example2 a:link {color: yellow; background: black} .example2 a:visited {color: white; background: black} .example2 a:active {color: red; background: black}

How can I show HTML examples without them being interpreted as part of my document?
Within the HTML example, first replace the "&" character with "&amp;" everywhere it occurs. Then replace the "&lt;" character with "<" and the "&gt;" character with ">" in the same way. Note that it may be appropriate to use the CODE and/or PRE elements when displaying HTML examples.
How do I get special characters in my HTML? The special case of the less-than ('<'), greater-than ('>'), and ampersand ('&') characters. In general, the safest way to write HTML is in US-ASCII (ANSI X3.4, a 7-bit code), expressing characters from the upper half of the 8-bit code by using HTML entities. Working with 8-bit characters can also be successful in many practical situations: Unix and MS-Windows (using Latin-1), and also Macs (with some reservations). Latin-1 (ISO-8859-1) is intended for English, French, German, Spanish, Portuguese, and various other western European languages. (It is inadequate for many languages of central and eastern Europe and elsewhere, let alone for languages not written in the Roman alphabet.) On the Web, these are the only characters reliably supported. In particular, characters 128 through 159 as used in MS-Windows are not part of the ISO-8859-1 code set and will not be displayed as Windows users expect. These characters include the em dash, en dash, curly quotes, bullet, and trademark symbol; neither the actual character (the single byte) nor its nnn; decimal equivalent is correct in HTML. Also, ISO-8859-1 does not include the Euro currency character. (See the last paragraph of this answer for more about such characters.) On platforms whose own character code isn't ISO-8859-1, such as MS-DOS and Mac OS, there may be problems: you have to use text transfer methods that convert between the platform's own code and ISO-8859-1 (e.g., Fetch for the Mac), or convert separately (e.g., GNU recode). Using 7-bit ASCII with entities avoids those problems, but this FAQ is too small to cover other possibilities in detail. If you run a web server (httpd) on a platform whose own character code isn't ISO-8859-1, such as a Mac or an IBM mainframe, then it's the job of the server to convert text documents into ISO-8859-1 code when sending them to the network. If you want to use characters not in ISO-8859-1, you must use HTML 4 or XHTML rather than HTML 3.2, choose an appropriate alternative character set (and for certain character sets, choose the encoding system too), and use one method or other of specifying this. Should I put quotes around attribute values? It is never wrong to quote attribute values, and many people recommend quoting all attribute values even when the quotation marks are technically optional. XHTML 1.0 requires all attribute values to be quoted. Like previous HTML specifications, HTML 4 allows attribute values to remain unquoted in many circumstances (e.g., when the value contains only letters and digits). Be careful when your attribute value includes double quotes, for instance when you want ALT text like "the "King of Comedy" takes a bow" for an image. Humans can parse that to know where the quoted material ends, but browsers can't. You have to code the attribute value specially so that the first interior quote doesn't terminate the value prematurely. There are two main techniques:

* Escape any quotes inside the value with &#34; so you don't terminate the value prematurely: ALT="the &#34;King of Comedy&#34; takes a bow". * Use single quotes to enclose the attribute value: ALT='the "King of Comedy" takes a bow'.

10
Both these methods are correct according to the specification and are supported by current browsers, but both were poorly supported in some earlier browsers. The only truly safe advice is to rewrite the text so that the attribute value need not contain quotes, or to change the interior double quotes to single quotes, like this: ALT="the 'King of Comedy' takes a bow".
Posting Copy and Paste HTML For those wanting to post direct Copy and Paste HTML on screen without the use of spaces or *s etc. and the need to explain those substitutions: Use &lt; to substitute for each opening tag < in each tagged set of HTML. Example, typing the following: &lt;a href="http://www.yourname.com">&lt;img src="http://pics.yourname.com/aw/pics/mask.gif">&lt;/a> Will show up on screen as: <a href="http://www.yourname.com"><img src="http://pics.yourname.com/aw/pics/mask.gif"></a> HTML for Lists 1. Bulleted Lists: <ul> begins a bulleted, indented list. Each item in the list is then prefaced with the <li> tag. It is not necessary to insert a break at the end of each line -- the <li> tag automatically creates a new line.

* with <li type=disc> * with <li type=square> * with <li type=circle> 2. Numbered Lists: <ol> begins a numbered, indented list. Each item in the list is then prefaced with the <li> tag. You need to close the list with the </ol> tag. Note: You can expand the <ol> to specify the TYPE of numbering: <ol> 1 (decimal numbers: 1, 2, 3, 4, 5, ...) <ol type="a"> a (lowercase alphabetic: a, b, c, d, e, ...) <ol type="A"> A (uppercase alphabetic: A, B, C, D, E, ...) <ol type="i"> i (lowercase Roman numerals: i, ii, iii, iv, v, ...) <ol type="I"> I (uppercase Roman numerals: I, II, III, IV, V, ...)
Are there any problems with using tables for layout? On current browsers, the entire table must be downloaded and the dimensions of everything in the table must to be known before the table can be rendered. That can delay the rendering of your content, especially if your table contains images without HEIGHT or WIDTH attributes. If any of your table's content is too wide for the available display area, then the table stretches to accomodate the oversized content. The rest of the content then adjusts to fit the oversized table rather than fitting the available display area. This can force your readers to scroll horizontally to read your content, or can cause printed versions to be cropped. For readers whose displays are narrower than the author anticipated, fixed-width tables cause the same problems as other oversized tables. For readers whose displays are wider than the author anticipated, fixed-width tables cause extremely wide margins, wasting much of the display area. For readers who need larger fonts, fixed-width tables can cause the content to be displayed in short choppy lines of only a few words each. Many browsers are especially sensitive to invalid syntax when tables are involved. Correct syntax is especially critical. Even with correct syntax, nested tables may not display

11
correctly in older versions of Netscape Navigator. Some browsers ignore tables, or can be configured to ignore tables. These browsers will ignore any layout you've created with tables. Also, search engines ignore tables. Some search engines use the text at the beginning of a document to summarize it when it appears in search results, and some index only the first n bytes of a document. When tables are used for layout, the beginning of a document often contains many navigation links that appear before than actual content. Many versions of Navigator have problems linking to named anchors when they are inside a table that uses the ALIGN attribute. These browsers seem to associate the named anchor with the top of the table, rather than with the content of the anchor. You can avoid this problem by not using the ALIGN attribute on your tables. If you use tables for layout, you can still minimize the related problems with careful markup. Avoid placing wide images, PRE elements with long lines, long URLs, or other wide content inside tables. Rather than a single full-page layout table, use several independent tables. For example, you could use a table to lay out a navigation bar at the top/bottom of the page, and leave the main content completely outside any layout tables.
How do I eliminate the blue border around linked images? In your HTML, you can specify the BORDER attribute for the image: <a href=...><img src=... alt=... border="0"></a> However, note that removing the border that indicates an image is a link makes it harder for users to distinguish quickly and easily which images on a web page are clickable. How do I eliminate the space around/between my images? If your images are inside a table, be sure to set the BORDER, CELLSPACING, and CELLPADDING attributes to 0. Extra space between images is often created by whitespace around the <IMG> tag in the markup. It is safe to use newlines inside a tag (between attributes), but not between two tags. For example, replace this:

<td ...> <img src=... alt=...> <img src=... alt=...> </td> with this: <td ...><img src=... alt=...><img src=... alt=...></td> According to the latest specifications, the two should be equivalent. However, common browsers do not comply with the specifications in this situation. Finally, extra space between images can appear in documents that trigger the "standards" rendering mode of Gecko-based browsers like Mozilla and Firefox.

How can I specify colors?


If you want others to view your web page with specific colors, the most appropriate way is to suggest the colors with a style sheet. Cascading Style Sheets use the color and background-color properties to specify text and background colors. To avoid conflicts between the reader's default colors and those suggested by the author, these two properties should always be used together. With HTML, you can suggest colors with the TEXT, LINK, VLINK (visited link), ALINK (active link), and BGCOLOR (background color) attributes of the BODY element.

12
Note that these attributes are deprecated by HTML 4. Also, if one of these attributes is used, then all of them should be used to ensure that the reader's default colors do not interfere with those suggested by the author. Here is an example: <body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#000080"> Authors should not rely on the specified colors since browsers allow their users to override document-specified colors.
How do I get form data emailed to me? The only reliable mechanism for processing form submissions is with a server-side (e.g., CGI) program. To send form data to yourself via email, you should use a server-side program that processes the form submission and sends the data to your email address. Some web service providers make standard form-to-email programs available to their customers. Check with your service provider for details. If you can install CGI programs on your own server, see the answer to the previous question for a list of useful resources. If you can't run CGI programs on your own server, you can use a remotely hosted form-toemail services. Note that the provider of a remotely hosted service will have access to any data submitted via the service. Forms that use action="mailto:..." are unreliable. According to the HTML specifications, form behavior is explicitly undefined for mailto URIs (or anything else other than HTTP URIs). They may work one way with one software configuration, may work other ways in other software configurations, and may fail completely in other software configurations. Can I prevent a form from being submitted again? No. The server-side (e.g., CGI) program that processes the form submission must handle duplicate submissions gracefully. You could generate the form with a server-side (e.g., CGI) program that adds a hidden field with a unique session ID. Then the server-side program that processes the form submission can check the session ID against a list of previously used session IDs. If the session ID has already been used, then an appropriate action can be taken (e.g., reject the submission, or update the previously submitted data). Ultimately, your server-side program must be smart enough to handle resubmitted data. But you can avoid getting resubmitted data by not expiring the confirmation page from form submissions. Since you want to expire pages quickly when they have transient data, you might want to avoid putting transient data on the confirmation page. You could provide a link to a database query that returns transient data though. How can I allow file uploads to my web site? These things are necessary for Web-based uploads:

* An HTTP server that accepts uploads. * Access to the /cgi-bin/ to put the receiving script. Prewritten CGI file-upload scripts are available. * A form implemented something like this: <form method="post" enctype="multipart/form-data" action="fup.cgi"> File to upload: <input type=file name=upfile><br> Notes about the file: <input type=text name=note><br> <input type=submit value=Press> to upload the file! </form> Not all browsers support form-based file upload, so try to give alternatives where possible.

13

The Perl CGI.pm module supports file upload. The most recent versions of the cgi-lib.pl library also support file upload. Also, if you need to do file upload in conjunction with form-to-email, the Perl package MIME::Lite handles email attachments.
How can I require that fields be filled in, or filled in correctly? Have the server-side (e.g., CGI) program that processes the form submission send an error message if the field is not filled in properly. Ideally, this error message should include a copy of the original form with the original (incomplete or incorrect) data filled in as the default values for the form fields. The Perl CGI.pm module provides helpful mechanisms for returning partially completed forms to the user. In addition, you could use JavaScript in the form's ONSUBMIT attribute to check the form data. If JavaScript support is enabled, then the ONSUBMIT event handler can inform the user of the problem and return false to prevent the form from being submitted. Note that the server-side program should not rely upon the checking done by the clientside script. How do I change the title of a framed document? The title displayed is the title of the frameset document rather than the titles of any of the pages within frames. To change the title displayed, link to a new frameset document using TARGET="_top" (replacing the entire frameset). How do I link an image to something? Just use the image as the link content, like this:

<a href=...><img src=... alt=...></a>


Should I end my URLs with a slash? The URL structure defines a hierarchy similar to a filesystem's hierarchy of subdirectories or folders. The segments of a URL are separated by slash characters ("/"). When navigating the URL hierarchy, the final segment of the URL (i.e., everything after the final slash) is similar to a file in a filesystem. The other segments of the URL are similar to the subdirectories and folders in a filesystem. When resolving relative URLs (see the answer to the previous question), the browser's first step is to strip everything after the last slash in the URL of the current document. If the current document's URL ends with a slash, then the final segment (the "file") of the URL is null. If you remove the final slash, then the final segment of the URL is no longer null; it is whatever follows the final remaining slash in the URL. Removing the slash changes the URL; the modified URL refers to a different document and relative URLs will resolve differently. For example, the final segment of the URL http://www.mysite.com/faq/html/ is empty; there is nothing after the final slash. In this document, the relative URL all.html resolves to http://www.mysite.com/faq/html/all.html (an existing document). If the final slash is omitted, then the final segment of the modified URL http://www.mysite.com/faq/html is "html". In this (nonexistent) document, the relative URL all.html would resolve to http://www.mysite.com/faq/all.html (another nonexistent document). When they receive a request that is missing its final slash, web servers cannot ignore the missing slash and just send the document anyway. Doing so would break any relative URLs in the document. Normally, servers are configured to send a redirection message when they receive such a request. In response to the redirection message, the browser requests the correct URL, and then the server sends the requested document. (By the way, the browser does not and cannot correct the URL on its own; only the server can

14
determine whether the URL is missing its final slash.) This error-correction process means that URLs without their final slash will still work. However, this process wastes time and network resources. If you include the final slash when it is appropriate, then browsers won't need to send a second request to the server. The exception is when you refer to a URL with just a hostname (e.g., http://www.mysite.com). In this case, the browser will assume that you want the main index ("/") from the server, and you do not have to include the final slash. However, many regard it as good style to include it anyway.

How do I specify a specific combination of frames instead of the default document?


This is unfortunately not possible. When you navigate through a site using frames, the URL will not change as the documents in the individual frames change. This means that there is no way to indicate the combination of documents that make up the current state of the frameset. The author can provide multiple frameset documents, one for each combination of frame content. These frameset documents can be generated automatically, perhaps being created on the fly by a CGI program. Rather than linking to individual content documents, the author can link to these separate frameset documents using TARGET="_top". Thus, the URL of the current frameset document will always specify the combination of frames being displayed, which allows links, bookmarks, etc. to function normally.
How do I link to a location in the middle of an HTML document? First, label the destination of the link. The old way to label the destination of the link was with an anchor using the NAME attribute. For example: <h2><a name="section2">Section 2: Beyond Introductions</a></h2>

The modern way to label the destination of the link is with an ID attribute. For example: <h2 id="section2">Section 2: Beyond Introductions</h2> Second, link to the labeled destination. The URL is the URL of the document, with "#" and the value of the NAME or ID attribute appended. Continuing the above examples, elsewhere in the same document you could use: <a href="#section2">go to Section 2</a> Similarly, in another document you could use: <a href="thesis.html#section2">go to Section 2 of my thesis</a>
How do I create a link? Use an anchor element. The HREF attribute specifies the URL of the document that you want to link to. The following example links the text "Web Authoring FAQ" to <URL:http://www.htmlhelp.com/faq/html/>: <A HREF="http://www.yoursite.com/faq/html/">Web Authoring FAQ</A> How do I create a link that opens a new window? <a target="_blank" href=...> opens a new, unnamed window. <a target="example" href=...> opens a new window named "example", provided that a window or frame by that name does not already exist. Note that the TARGET attribute is not part of HTML 4 Strict. In HTML 4 Strict, new windows can be created only with JavaScript. links that open new windows can be annoying to your readers if there is not a good reason for them.

15
How do I let people download a file from my page? Once the file is uploaded to the server, you need only use an anchor reference tag to link to it. An example would be: <a href="../files/foo.zip">Download Foo Now! (100kb ZIP)</a> How do I create a button which acts like a link? This is best done with a small form:

<FORM ACTION="[URL]" METHOD=GET> <INPUT TYPE=submit VALUE="Text on button"> </FORM> If you want to line up buttons next to each other, you will have to put them in a one-row table, with each button in a separate cell. Note that search engines might not find the target document unless there is a normal link somewhere else on the page. A go-to-other-page button can also be coded in JavaScript, but the above is standard HTML and works for more readers.
How can I make a form with custom buttons? Rather than a normal submit button (<input type="submit" ...>), you can use the image input type (<input type="image" ...>). The image input type specifies a graphical submit button that functions like a server-side image map. Unlike normal submit buttons (which return a name=value pair), the image input type returns the x-y coordinates of the location where the user clicked on the image. The browser returns the x-y coordinates as name.x=000 and name.y=000 pairs. For compatability with various non-graphical browsing environments, the VALUE and ALT attributes should be set to the same value as the NAME attribute. For example: <input type="image" name="Send" alt="Send" value="Send" src="send-button.gif"> For the reset button, one could use <button type="reset" ...>, JavaScript, and/or style sheets, although none of these mechanisms work universally. How do I specify page breaks in HTML? There is no way in standard HTML to specify where page breaks will occur when printing a page. HTML was designed to be a device-independent structural definition language, and page breaks depend on things like the fonts and paper size that the person viewing the page is using. How do I remove the border around frames? Removing the border around frames involves both not drawing the frame borders and eliminating the space between the frames. The most widely supported way to display borderless frames is <FRAMESET ... BORDER=0 FRAMEBORDER=0 FRAMESPACING=0>. Note that these attributes are proprietary and not part of the HTML 4.01 specifications. (HTML 4.01 does define the FRAMEBORDER attribute for the FRAME element, but not for the FRAMESET element.) Also, removing the border around a frame makes it difficult to resize it, as this border is also used in most GUIs to change the size of the frame.

Which should I use, &entityname; or &#number; ?


In HTML, characters can be represented in three ways: 1. a properly coded character, in the encoding specified by the "charset" attribute of the

16
"Content-type:" header; 2. a character entity (&entityname;), from the appropriate HTML specification (HTML 2.0/3.2, HTML 4, etc.); 3. a numeric character reference (&#number;) that specifies the Unicode reference of the desired character. We recommend using decimal references; hexadecimal references are less widely supported. In theory these representations are equally valid. In practice, authoring convenience and limited support by browsers complicate the issue. HTTP being a guaranteed "8-bit clean" protocol, you can safely send out 8-bit or multibyte coded characters, in the various codings that are supported by browsers. A. HTML 2.0/3.2 (Latin-1) By now there seems no convincing reason to choose &entityname; versus &#number;, so use whichever is convenient. If you can confidently handle 8-bit-coded characters this is fine too, probably preferred for writing heavily-accented languages. Take care if authoring on non-ISO-8859-based platforms such as Mac, Psion, IBM mainframes etc., that your upload technique delivers a correctly coded document to the server. Using &amp;-representations avoids such problems. B. A single repertoire other than Latin-1 In such codings as ISO-8859-7 Greek, koi8-r Russian Cyrillic, and Chinese, Japanese and Korean (CJK) codings, use of coded characters is the most widely supported and used technique. Although not covered by HTML 3.2, browsers have supported this quite widely for some time now; it is a valid option within the HTML 4 specifications--use a validator such as the WDG HTML Validator or the W3C HTML Validation Service which supports HTML 4 and understands different character encodings. Browser support for coded characters may depend on configuration and font resources. In some cases, additional programs called "helpers" or "add-ins" supply virtual fonts to browsers. "Add-in" programs have in the past been used to support numeric references to 15-bit or 16-bit code protocols such as Chinese Big5 or Chinese GB2312. In theory you should be able to include not only coded characters but also Unicode numeric character references, but browser support is generally poor. Numeric references to the "charset-specified" encoding may appear to produce the desired characters on some browsers, but this is wrong behavior and should not be used. Character entities are also problematical, aside from the HTML-significant characters <, &amp; etc. C. Internationalization per HTML 4 Recent versions of the popular browsers have support for some of these features, but at time of writing it seems unwise to rely on this when authoring for a general audience.
Is there a way to prevent getting framed? "Getting framed" refers to having your documents displayed within someone else's

17
frameset without your permission. This can happen accidentally (the frameset author forgot to use TARGET="_top" when linking to your document) or intentionally (the frameset author wanted to display your content with his/her own navigation or banner frames). To avoid "framing" other people's documents, you must add TARGET="_top" to all links that lead to documents outside your intended scope. Unfortunately, there is no reliable way to specify that a particular document should be displayed in the full browser window, rather than in the current frame. One workaround is to use <BASE TARGET="_top"> in the document, but this only specifies the default target frame for links in the current document, not for the document itself. If the reader's browser has JavaScript enabled, the following script will automatically remove any existing framesets: <script type="text/javascript"> if (top.frames.length!=0) { if (window.location.href.replace) top.location.replace(self.location.href); else top.location.href=self.document.href;

}
</script> An alternative script is <script type="text/javascript"> function breakOut() { if (self != top) window.open("my URL","_top","");

}
</script> </HEAD> <BODY onLoad="breakOut()">
Why aren't my frames the exact size I specified? Older versions of Netscape Navigator seems to convert pixel-based frame dimensions to whole percentages, and to use those percentage-based dimensions when laying out the frames. Thus, frames with pixel-based dimensions will be rendered with a slightly different size than that specified in the frameset document. The rounding error will vary depending on the exact size of the browser window. Furthermore, Navigator seems to store the percentage-based dimensions internally, rather than the original pixel-based dimensions. Thus, when a window is resized, the frames are redrawn based on the new window size and the old percentage-based dimensions. There is no way to prevent this behavior. To accommodate it, you should design your site to adapt to variations in the frame dimensions. This is another situation where it is a good idea to accommodate variations in the browser's presentation. How can I specify background images? With HTML, you can suggest a background image with the BACKGROUND attribute of the BODY element. Here is an example: <body background="imagefile.gif" bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#800080" alink="#000080"> If you specify a background image, you should also specify text, link, and background

18
colors since the reader's default colors may not provide adequate contrast against your background image. The background color may be used by those not using your background image. Authors should not rely on the specified background image since browsers allow their users to disable image loading or to override document-specified backgrounds.
How can I copy something from a webpage to my webpage? 1: Plaintext or any text information viewable from your browser can be easily copied like any other text from any other file. 2; HTML and web scripts - you will need to view the web page's source code. In the page's source code, copying the <script> and </script> tags as well as all the information inbetween these tags will usually enable the script to work on your web page. 3: Images, sounds, or movies - Almost all images, sounds, and movies can be copied to your computer and then viewed on your webpage. Images can be easily copied from a webpage by right-clicking an image and selecting "Save Picture as" or "Save Image as". Unless the sound or movies file has a direct link to download and save the file to a specified location on your hard disk drive or to view your Internet browser's cache and locate the sound or movie file saved in the cache. 4. Embedded objects - Looking at the source code of the object to determine the name of the file and how it is loaded, and copy both the code and the file.

Is it possible to make the HTML source not viewable?


In short, there is no real method or script for making standard HTML source code not viewable. You may consider doing any of the below if they are concerned about your source code. 1. Create the web page in Macromedia Flash or a similar program. The visitor would need to download the Macromedia Flash plug-in and would be unable to view the source code for the flash applet. 2. There are various scripts that will disable the right click feature, preventing the user from saving images or viewing the source. However, this will not protect the source code of your page. For example, Internet Explorer users may still click "View" and "Source" to view the source code of the page, or a user could disable scripts and images can be saved by simply saving the web page to the hard drive. 3. There are several programs that will help scramble your code, making it difficult (not impossible) to read. Again, this is not going to prevent someone from viewing your code.
Why doesn't my title show up when I click "check it out"? You're probably looking at the wrong part of the screen. The Title usually shows up in the Title Bar on the Window, to the left of the minimize/maximize buttons on graphical browsers. How do I make a thumbnail for my image(s)? Thumbnails are very useful, but they take a little bit of time to make. All you need is a graphics editing program that has functions to resize an image (sometimes it's under a function called image attributes). Be advised--when you have made a thumbnail, you will need to save it as something different than the original. Also, you will generally want to link to the larger graphic when you are done.

Here are the steps: 1. Load a copy of the image into your graphics editing program. 2. Determine the ratio the thumbnail to be. (Do you want it to be half the size? One third

19
of the size? One quarter of the size? One tenth of the size?) 3. Find the resize (or change attributes) function of your program. Most programs will recogize a percentage, for example you can type in 25% for height and width if you want the thumbnail to be a quarter of the size. (It it doesn't do percentages, you can calculate it by multiplying the pixels by the percentage. If you have a graphic that is 400 by 100, and you want it 25% of the size, multiple each measurement by .25. In this case, you'll get 100 and 25.) 4. Once you are satisfied with the thumbnail, think of a name for the image. Choose Save As and enter that name. (Tip: I like to just add t after the image name. For taco.jpg I'd use tacot.jpg) 5. Upload the image to your site, and edit your HTML to load the new image name with the new, smaller size. If you wish, you can link to the larger image around the image. Example: You have taco.jpg which is 400 pixels wide and 100 pixels high. You made a thumbnail of it called tacot.jpg, which is now 100 pixels wide and 25 pixels high. After you have both images uploaded, here's the code: <a href="taco.jpg"><img src="tacot.jpg" width=100 height=25 border=0 alt="click for larger taco"></a> You'll find border=0 to be helpful in eliminating a link-colored box around your thumbnail.

What is the difference between the HTML form methods GET and POST?
The method parameter specifies which method the client is using to send information to the WEB server. The method determines which parameter you will find the CGI request data in: * POST - post_args * GET - httpargs
How do I rename all the files from .htm to .html after copying them from a PC to a UNIX machine? UNIX's mv (`move') command won't handle wildcard filenames. However, there's a program called htmaddl (for `HTM-add-"L"'), so you can login and type htmaddl. This will rename all .htm files to .html

If you haven't got this program on your UNIX machine, you can type it into a file called htmaddl: #! /bin/sh for f in *.htm; do base=`basename $f .htm` mv $f $base.html done After saving it and exiting your editor, make it executable by typing the command chmod ugo+x htmaddl Best of all, move it into your ~/bin directory, or ask your WebMeister to put it in /usr/local/bin so everyone can use it.

20
How do I put sounds for older versions of Internet Explorer? For older versions of Internet Explorer, this technique was used <BG SOUND="sound.ext">. Can I use any HTML in the box? Yes. Any HTML tag that your browser supports will work in the box. So you can carry tags from chapters to chapters and mix and match... How to transferring user to new web page automatically? You will need to use the below meta tag. <META HTTP-EQUIV="Refresh" CONTENT="2"; URL="http://www.yourname.com"> Placing the above tag in your <HEAD></HEAD> will load yousite.com in 2 seconds. Changing the 2 value on CONTENT="2" to another value will increase or decrease the delay until loading the new page. I'm trying to `include' a HTML document in another document...Is there a way to do this? Yes, there are several ways to do this. But remember, HTML is not a programming language - it doesn't have `directives': it's a markup language, so trying to compare it to C or Pascal is not going to be very meaningful.

SGML already provides the standard way to do this, using an entry in the DocType Declaration for a file: <!doctype html public "-//IETF//DTD HTML 3.0//EN" [ <!entity foo system "bar.html"> ]> ... and then later when you want to include the file ... &foo; This is the General Entity mechanism used universally in normal SGML work and does exactly what is wanted, with the added benefit that you can have multiple occurrences of &foo; if you need to include some text at more than one place. Unfortunately none of the browsers except Panorama support it, basically because very few of the programmers who write browsers bothered to read up on what can be done. * The second way is to use the facilities of your server. This has to be enabled by someone with access to the server configuration files (ask your WebMeister). For example, the NCSA server lets you embed a command inside an SGML comment: <!--#exec cmd="cat myfile.html"--> Provided this occurs in a file with a special file type (eg .shtml, and this is what has to be specified in the server configuration), the server will parse the file and send out the result of the command embedded in the document. * There is in fact a vastly easier way to do this. SGML provides a PI mechanism (Processing Instruction) in the form: <?cat myfile> SGML/HTML couldn't care what you put inside (except it must not, for obvious reasons, contain the `>' character!). This would be a great way to specify a page break, for example: suppose you were processing an SGML file using PostScript, you could say

21
<?showpage>...but again, none of the browsers except Panorama support this, again because they guys who write them have never bothered to actually read up on how SGML works.

How do I keep people from stealing my source code and/or images?


Because copies of your HTML files and images are stored in cache, it is impossible to prevent someone from being able to save them onto their hard drive. If you are concerned about your images, you may wish to embed a watermark with your information into the image. Consult your image editing program's help file for more details.
The colors on my page look different when viewed on a Mac and a PC. The Mac and the PC use slightly different color palettes. There is a 216 "browser safe" color palette that both platforms support; the Microsoft color picker page has some good information and links to other resources about this. In addition, the two platforms use different gamma (brightness) values, so a graphic that looks fine on the Mac may look too dark on the PC. The only way to address this problem is to tweak the brightness of your image so that it looks acceptable on both platforms. How do you create tabs or indents in Web pages? There was a tag proposed for HTML 3.0, but it was never adopted by any major browser and the draft specification has now expired. You can simulate a tab or indent in various ways, including using a transparent GIF, but none are quite as satisfactory or widely supported as an official tag would be. My page looks good on one browser, but not on another. There are slight differences between browsers, such as Netscape Navigator and Microsoft Internet Explorer, in areas such as page margins. The only real answer is to use standard HTML tags whenever possible, and view your pages in multiple browsers to see how they look. How do I make sure my framed documents are displayed inside their frameset? When the sub-documents of a frameset state are accessed directly, they appear without the context of the surrounding frameset. If the reader's browser has JavaScript support enabled, the following script will restore the frameset:

<SCRIPT TYPE="text/javascript"> if (parent.location.href == self.location.href) { if (window.location.href.replace) window.location.replace('frameset.html'); else // causes problems with back button, but works window.location.href = 'frameset.html';

}
</SCRIPT> A more universal approach is a "restore frames" link: <A HREF="frameset.html" TARGET="_top">Restore Frames Note that in either case, you must have a separate frameset document for every content document. If you link to the default frameset document, then your reader will get the default content document, rather than the content document he/she was trying to access.

22
These frameset documents should be generated automatically, to avoid the tedium and inaccuracy of creating them by hand. Note that you can work around the problem with bookmarking frameset states by linking to these separate frameset documents using TARGET="_top", rather than linking to the individual content documents.
How do I update two frames at once? There are two basic techniques for updating multiple frames with a single link: The HTMLbased technique links to a new frameset document that specifies the new combination of frames. The JavaScript-based solution uses the onClick attribute of the link to update the additional frame (or frames).

The HTML-based technique can link to a new frameset document with the TARGET="_top" attribute (replacing the entire frameset). However, there is an alternative if the frames to be updated are part of a nested frameset. In the initial frameset document, use a secondary frameset document to define the nested frameset. For example: <frameset cols="*,3*"> <frame src="contents.html" name="Contents"> <frame src="frameset2.html" name="Display"> <noframes> <!-- Alternative non-framed version --> </body></noframes> </frameset> A link can now use the TARGET="Display" attribute to replace simultaneously all the frames defined by the frameset2.html document. The JavaScript-based solution uses the onClick attribute of the link to perform the secondary update. For example: <a href="URL1" target="Frame1" onClick="top.Frame2.location='URL2';">Update frames The link will update Frame1 with URL1 normally. If the reader's browser supports JavaScript (and has it enabled), then Frame2 will also be updated (with URL2).
Can I have two or more Submit buttons in the same form? Yes. This is part of HTML 2.0 Forms support (some early browsers did not support it, but browser coverage is now excellent). The submit buttons must have a NAME attribute. The optional VALUE attribute can be used to specify different text for the different submit buttons. To determine which submit button was used, you need to use different values for the NAME and/or VALUE attributes. Browsers will send to the server the name=value pair of the submit button that was used. Here is an example:

<input type="submit" name="join" value="I want to join now"> <input type="submit" name="info" value="Please send full details"> Note that if you are using image submit buttons, you need to provide different NAME attributes for them too. Also, browser behavior can be inconsistent when the form is submitted without a submit button (e.g., by hitting ENTER). If you're unsure what results you're going to get when you submit your form, TipJar has a standard script which you can use. Code this, for example (assuming method "post"): <form method="post" action="http://www.yoursite.com/cgi-bin/test">

23
and then go through the motions of submitting your form. The TipJar server decodes the form input, and displays the result to you.
How do I make a link or form in one frame update another frame? In the frameset document (the HTML document containing the <frameset> <frame> tags), make sure to name the individual frames using the NAME attribute. The following example creates a top frame named "navigation" and a bottom frame named "content": <frameset rows="*,3*"> <frame name="navigation" src="navigation.html"> <frame name="content" src="content.html"> <noframes><body> <!-- Alternative non-framed version --> </body></noframes> </frameset>

Then, in the document with the link, use the TARGET attribute to specify which frame should be used to display the link. (The value of the TARGET attribute should match the value of the target frame's NAME attribute.) For example: <a target="content" href=...> To target a form submission, use the TARGET attribute of the FORM element, like this: <form target="content" action=...> Note that when forms are processed entirely by JavaScript, the target frame must be specified in the JavaScript. The value of the TARGET attribute is irrelevant. Normally, the default target frame is the current frame ("_self"). To change the default target for every link/form on the page, use the TARGET attribute of the BASE element, like this: <base target="content">

When I try to upload my site, all my images are X's. How do I get them to load correctly?
They are a few reasons that this could happen. The most common are: 1. You're attempting to use a .bmp or .tif or other non-supported file format. You can only use .gif and .jpg on the web. You must convert files that are not .gif or .jpg into a .gif or .jpg with your image/graphics program. 2. You've forgotten to upload the graphic files. Double-Check. 3. You've incorrectly linked to the images. When you are starting out, try just using the file name in the <img> tag. If you have cat.jpg, use img src="cat.jpg">. 4. Image file names are case-sensitive. If your file is called CaT.JpG, you cannot type cat.jpg, you must type CaT.JpG exactly in the src. 5. If all of the above fail, re-upload the image in BINARY mode. You may have accidentally uploaded the image in ASCII mode.
Is there a site that shows which tags work on which browsers? There have been several attempts to do this, but I'm not aware of any really good source of comparisons between the browsers. The trouble is that there are many different versions of each browser, and many different tags. All current browsers should support the tags in the official HTML 3.2 specification, but the major ones also support nonstandard tags and

24
sometimes have slightly different implementations. One place that has fairly good compatibility info is Browsercaps.
Why does the browser show my plain HTML source? If Microsoft Internet Explorer displays your document normally, but other browsers display your plain HTML source, then most likely your web server is sending the document with the MIME type "text/plain". Your web server needs to be configured to send that filename with the MIME type "text/html". Often, using the filename extension ".html" or ".htm" is all that is necessary. If you are seeing this behavior while viewing your HTML documents on your local Windows filesystem, then your text editor may have added a ".txt" filename extension automatically. You should rename filename.html.txt to filename.html so that Windows will treat the file as an HTML document. How can I display an image on my page? Use an IMG element. The SRC attribute specifies the location of the image. The ALT attribute provides alternate text for those not loading images. For example:

<img src="logo.gif" alt="ACME Products">


Why do my links open new windows rather than update an existing frame? If there is no existing frame with the name you used for the TARGET attribute, then a new browser window will be opened, and this window will be assigned the name you used. Furthermore, TARGET="_blank" will open a new, unnamed browser window. In HTML 4, the TARGET attribute value is case-insensitive, so that abc and ABC both refer to the same frame/window, and _top and _TOP both have the same meaning. However, most browsers treat the TARGET attribute value as case-sensitive and do not recognize ABC as being the same as abc, or _TOP as having the special meaning of _top. Also, some browsers include a security feature that prevents documents from being hijacked by third-party framesets. In these browsers, if a document's link targets a frame defined by a frameset document that is located on a different server than the document itself, then the link opens in a new window instead. How do I get out of a frameset? If you are the author, this is easy. You only have to add the TARGET attribute to the link that takes readers to the intended 'outside' document. Give it the value of _top. In many current browsers, it is not possible to display a frame in the full browser window, at least not very easily. The reader would need to copy the URL of the desired frame and then request that URL manually. I would recommend that authors who want to offer readers this option add a link to the document itself in the document, with the TARGET attribute set to _top so the document displays in the full window if the link is followed. How do I make a frame with a vertical scrollbar but without a horizontal scrollbar? The only way to have a frame with a vertical scrollbar but without a horizontal scrollbar is to define the frame with SCROLLING="auto" (the default), and to have content that does not require horizontal scrolling. There is no way to specify that a frame should have one scrollbar but not the other. Using SCROLLING="yes" will force scrollbars in both directions (even when they aren't needed), and using SCROLLING="no" will inhibit all scrollbars (even when scrolling is necessary to access the frame's content). There are no other values for the SCROLLING attribute.

25
Are there any problems with using frames? The fundamental problem with the design of frames is that framesets create states in the browser that are not addressable. Once any of the frames within a frameset changes from its default content, there is no longer a way to address the current state of the frameset. It is difficult to bookmark - and impossible to link or index - such a frameset state. It is impossible to reference such a frameset state in other media. When the sub-documents of such a frameset state are accessed directly, they appear without the context of the surrounding frameset. Basic browser functions (e.g., printing, moving forwards/backwards in the browser's history) behave differently with framesets. Also, browsers cannot identify which frame should have focus, which affects scrolling, searching, and the use of keyboard shortcuts in general. Furthermore, frames focus on layout rather than on information structure, and many authors of framed sites neglect to provide useful alternative content in the NOFRAMES element. Both of these factors cause accessibility problems for browsers that differ significantly from the author's expectations and for search engines. Do search engines dislike frames? Search engines can link directly to framed content documents, but they cannot link to the combinations of frames for which those content documents were designed. This is the result of a fundamental flaw in the design of frames. Search engines try to provide their users with links to useful documents. Many framed content documents are difficult to use when accessed directly (outside their intended frameset), so there is little benefit if search engines offer links to them. Therefore, many search engines ignore frames completely and go about indexing more useful (non-framed) documents. Search engines will index your <NOFRAMES> content, and any content that is accessible via your

Set 2: HTML Interview Questions 1) What is an attribute ? Attribute helps you in actually customizing most of the tags present in HTML. An attribute is a keyword that you use in an opening tag to give more information to the web browser. This tag is very helpful in HTML. 2) Describe about element? tag has information about metadata of your web page. This tag holds information about keywords for search engines, refresh rates for client pull, and more. It connects value to names and it places information in HTTP headers which determine the pages behavior. It includes keywords about your webpage which are parsed and indexed by search engines for collecting information about your webpage. Also the display of your webpage on internet is chiefly dependent upon your keywords. 3) What is the difference between TT, KBD, SAMP? TT: - This tag displays text in monospace teletype font. This is useful to create teletype text. SAMP: -This tag styles text as sample program output. The ouput is usually displayed in a monospace font.

26

KBD: -This displays the text the user is supposed to enter, usually in bold or standard monospace font. The text which the user should enter is displayed in monospace font. 4) What are the different types of lists? Explain? There are three kinds of lists they are unordered lists, ordered lists and definition lists. * Unordered lists: -You can create them with elements like UL. Each item in the list gets its own element using the LI list item tag. * Ordered lists: -While unordered lists displays a simple bullet before each list item, Ordered lists use a number system of some kind to indicate that the terms are ordered in some way. Definition lists: -These lists include both terms and their definitions. You use the element to create these lists. This tag uses both unordered lists and ordered lists. 5) How do you customize columns in column groups? You can use the element to specify formatting for every column in a group, if you include these elements inside a element. The first element in a element sets the formatting and style for the first column. The next element sets the formatting and style for the next column. 6) Explain about iframe Internet explorer supports inline frames which are also called as floating frames. Inline frames can appear wherever you want them including in the middle of the page. All you have to do is specify the height and width of the frame after which you can load the HTML page into it. Inline frames are supported with the IFRAME element. 7) Explain about DATAFLD and DATASRC? DATAFLD names the column of the data source object that supplies the bound data. Set to alpha numeric characters. DATASRC guides the URL or ID of the data source object supplying data bound to this element. W3c says it should be a url; internet explorer says it should be a data source. 8) What are the different multimedia controls which IE supports? Internet explorer supports various controls and functions such as * Behaviors: -which creates special behavior elements for the page * Effects which lets you apply graphics filter to the page * Hotspot converts regions of the screen into clickable regions. * Mixer mixes WAV files * Path moves elements along a path creating animation * Sequence provides control for timing events * Sprite creates sprite based animations etc. 9) Explain about OBJECT and PARAM? OBJECT command is used to embed objects such as active controls in webpages, tasks of APPLET, EMBED, BGSOUND, SOUND and IMG elements. PARAM: -Supplies parameters to the object specified by the enclosing OBJECT or APPLET element. Structure graphic control tell you what to draw.

27

10) Explain about Z-Index? Z-Index lets you specify the stacking order of alayer. Layers that have higher Z-INDEX values go above those with lower z-index values, Z index values that are positive are stacked above their parents, while negative ones are stacked below their parents. 11) Explain EMBED and NOEMBED and their supporting tags? Embed lets you embed a plug in in a web page to play multimedia inline or anything else a plug in can do. There are three required attributes HEIGHT, WIDTH AND SRC. NOEMBED This tag displays text (hyperlinks) or HTML that doesnt use embedded components. This is used to display text, hyperlinks and no embedded HTML. 12) What is a MARQUEE element? The MARQUEE element is an internet explorer element that displays text in a moving marquee which can scroll, slide, or bounce in a horizontal strip. It is entirely dependent upon the programmer to set the size of the script in a MARQUEE. 13) Describe about server side image map? To create a server side image map, you use the ISMAP stand alone attribute of the IMG element. Surround the whole element that displays the map in a hyperlink element. The elements HREF attribute gives the URL of the map file you want to use. The map file specifies the clickable regions in the map. 14) Describe about the client side image maps? A programmer can create a client-side image maps by creating a element to define the clickable regions, in the element. You can then assign the name of the element to use the USEMAP attribute of the element, which inserts the actual image map into the webpage. When you are using netscape navigator you will be using internal anchors only. 15) Explain about FIELDSET, LEGEND, and LABEL? The FIELDSET, LEGEND, and elements are relatively new and let you group controls in a form visually. Use the FIELDSET element to group elements in a form together in a box, the LEGEND element to add a caption to the box, and the LABEL element to label the elements in the form. 16) How to refer controls in a form in code? We refer to controls in a form by specifying the entire url of the document document.formname.control. That is, the document object contains all other objects including the form you want to use and the form contains the control you want to reach, so to refer to a ctrl form code by suppling its full name:document.formname.control. 17) What exactly is HTML? HTML is known as hyper text mark up language. It contains many different features and tags through which you can format the text. It also enables you to create websites, text pages, etc. During these days HTML has grown very much in popularity because of its use and as a base for

28

many languages. There is also criticism for this language which is wide present in many different areas. Set 3: How can I require that fields be filled in, or filled in correctly? Have the server-side (e.g., CGI) program that processes the form submission send an error message if the field is not filled in properly. Ideally, this error message should include a copy of the original form with the original (incomplete or incorrect) data filled in as the default values for the form fields. The Perl CGI.pm module provides helpful mechanisms for returning partially completed forms to the user. In addition, you could use JavaScript in the form's ONSUBMIT attribute to check the form data. If JavaScript support is enabled, then the ONSUBMIT event handler can inform the user of the problem and return false to prevent the form from being submitted. Note that the server-side program should not rely upon the checking done by the clientside script. How do I change the title of a framed document? The title displayed is the title of the frameset document rather than the titles of any of the pages within frames. To change the title displayed, link to a new frameset document using TARGET="_top" (replacing the entire frameset). How do I link an image to something? Just use the image as the link content, like this: <a href=...><img src=... alt=...></a> Should I end my URLs with a slash? The URL structure defines a hierarchy similar to a filesystem's hierarchy of subdirectories or folders. The segments of a URL are separated by slash characters ("/"). When navigating the URL hierarchy, the final segment of the URL (i.e., everything after the final slash) is similar to a file in a filesystem. The other segments of the URL are similar to the subdirectories and folders in a filesystem. When resolving relative URLs (see the answer to the previous question), the browser's first step is to strip everything after the last slash in the URL of the current document. If the current document's URL ends with a slash, then the final segment (the "file") of the URL is null. If you remove the final slash, then the final segment of the URL is no longer null; it is whatever follows the final remaining slash in the URL. Removing the slash changes the URL; the modified URL refers to a different document and relative URLs will resolve differently. For example, the final segment of the URL http://www.mysite.com/faq/html/ is empty; there is nothing after the final slash. In this document, the relative URL all.html resolves to http://www.mysite.com/faq/html/all.html (an existing document). If the final slash is omitted, then the final segment of the modified URL http://www.mysite.com/faq/html is "html". In this (nonexistent) document, the relative URL all.html would resolve to http://www.mysite.com/faq/all.html (another nonexistent document). When they receive a request that is missing its final slash, web servers cannot ignore the

29

missing slash and just send the document anyway. Doing so would break any relative URLs in the document. Normally, servers are configured to send a redirection message when they receive such a request. In response to the redirection message, the browser requests the correct URL, and then the server sends the requested document. (By the way, the browser does not and cannot correct the URL on its own; only the server can determine whether the URL is missing its final slash.) This error-correction process means that URLs without their final slash will still work. However, this process wastes time and network resources. If you include the final slash when it is appropriate, then browsers won't need to send a second request to the server. The exception is when you refer to a URL with just a hostname (e.g., http://www.mysite.com). In this case, the browser will assume that you want the main index ("/") from the server, and you do not have to include the final slash. However, many regard it as good style to include it anyway. How do I specify a specific combination of frames instead of the default document? This is unfortunately not possible. When you navigate through a site using frames, the URL will not change as the documents in the individual frames change. This means that there is no way to indicate the combination of documents that make up the current state of the frameset. The author can provide multiple frameset documents, one for each combination of frame content. These frameset documents can be generated automatically, perhaps being created on the fly by a CGI program. Rather than linking to individual content documents, the author can link to these separate frameset documents using TARGET="_top". Thus, the URL of the current frameset document will always specify the combination of frames being displayed, which allows links, bookmarks, etc. to function normally. How do I link to a location in the middle of an HTML document? First, label the destination of the link. The old way to label the destination of the link was with an anchor using the NAME attribute. For example: <h2><a name="section2">Section 2: Beyond Introductions</a></h2> The modern way to label the destination of the link is with an ID attribute. For example: <h2 id="section2">Section 2: Beyond Introductions</h2> Second, link to the labeled destination. The URL is the URL of the document, with "#" and the value of the NAME or ID attribute appended. Continuing the above examples, elsewhere in the same document you could use: <a href="#section2">go to Section 2</a> Similarly, in another document you could use: <a href="thesis.html#section2">go to Section 2 of my thesis</a> How do I create a link? Use an anchor element. The HREF attribute specifies the URL of the document that you want to link to. The following example links the text "Web Authoring FAQ" to <URL:http://www.htmlhelp.com/faq/html/>: <A HREF="http://www.yoursite.com/faq/html/">Web Authoring FAQ</A>

30

How do I create a link that opens a new window? <a target="_blank" href=...> opens a new, unnamed window. <a target="example" href=...> opens a new window named "example", provided that a window or frame by that name does not already exist. Note that the TARGET attribute is not part of HTML 4 Strict. In HTML 4 Strict, new windows can be created only with JavaScript. links that open new windows can be annoying to your readers if there is not a good reason for them. How do I let people download a file from my page? Once the file is uploaded to the server, you need only use an anchor reference tag to link to it. An example would be: <a href="../files/foo.zip">Download Foo Now! (100kb ZIP)</a> How do I create a button which acts like a link? This is best done with a small form: <FORM ACTION="[URL]" METHOD=GET> <INPUT TYPE=submit VALUE="Text on button"> </FORM> If you want to line up buttons next to each other, you will have to put them in a one-row table, with each button in a separate cell. Note that search engines might not find the target document unless there is a normal link somewhere else on the page. A go-to-other-page button can also be coded in JavaScript, but the above is standard HTML and works for more readers. How can I make a form with custom buttons? Rather than a normal submit button (<input type="submit" ...>), you can use the image input type (<input type="image" ...>). The image input type specifies a graphical submit button that functions like a server-side image map. Unlike normal submit buttons (which return a name=value pair), the image input type returns the x-y coordinates of the location where the user clicked on the image. The browser returns the x-y coordinates as name.x=000 and name.y=000 pairs. For compatability with various non-graphical browsing environments, the VALUE and ALT attributes should be set to the same value as the NAME attribute. For example: <input type="image" name="Send" alt="Send" value="Send" src="send-button.gif"> For the reset button, one could use <button type="reset" ...>, JavaScript, and/or style sheets, although none of these mechanisms work universally. How do I specify page breaks in HTML? There is no way in standard HTML to specify where page breaks will occur when printing a page. HTML was designed to be a device-independent structural definition language, and page breaks depend on things like the fonts and paper size that the person viewing the page is using.

31

How do I remove the border around frames? Removing the border around frames involves both not drawing the frame borders and eliminating the space between the frames. The most widely supported way to display borderless frames is <FRAMESET ... BORDER=0 FRAMEBORDER=0 FRAMESPACING=0>. Note that these attributes are proprietary and not part of the HTML 4.01 specifications. (HTML 4.01 does define the FRAMEBORDER attribute for the FRAME element, but not for the FRAMESET element.) Also, removing the border around a frame makes it difficult to resize it, as this border is also used in most GUIs to change the size of the frame. Which should I use, &entityname; or &#number; ? In HTML, characters can be represented in three ways: 1. a properly coded character, in the encoding specified by the "charset" attribute of the "Content-type:" header; 2. a character entity (&entityname;), from the appropriate HTML specification (HTML 2.0/3.2, HTML 4, etc.); 3. a numeric character reference (&#number;) that specifies the Unicode reference of the desired character. We recommend using decimal references; hexadecimal references are less widely supported. In theory these representations are equally valid. In practice, authoring convenience and limited support by browsers complicate the issue. HTTP being a guaranteed "8-bit clean" protocol, you can safely send out 8-bit or multibyte coded characters, in the various codings that are supported by browsers. A. HTML 2.0/3.2 (Latin-1) By now there seems no convincing reason to choose &entityname; versus &#number;, so use whichever is convenient. If you can confidently handle 8-bit-coded characters this is fine too, probably preferred for writing heavily-accented languages. Take care if authoring on non-ISO-8859-based platforms such as Mac, Psion, IBM mainframes etc., that your upload technique delivers a correctly coded document to the server. Using &amp;-representations avoids such problems. B. A single repertoire other than Latin-1 In such codings as ISO-8859-7 Greek, koi8-r Russian Cyrillic, and Chinese, Japanese and Korean (CJK) codings, use of coded characters is the most widely supported and used technique. Although not covered by HTML 3.2, browsers have supported this quite widely for some time now; it is a valid option within the HTML 4 specifications--use a validator such as the WDG HTML Validator or the W3C HTML Validation Service which supports HTML 4 and understands different character encodings.

32

Browser support for coded characters may depend on configuration and font resources. In some cases, additional programs called "helpers" or "add-ins" supply virtual fonts to browsers. "Add-in" programs have in the past been used to support numeric references to 15-bit or 16-bit code protocols such as Chinese Big5 or Chinese GB2312. In theory you should be able to include not only coded characters but also Unicode numeric character references, but browser support is generally poor. Numeric references to the "charset-specified" encoding may appear to produce the desired characters on some browsers, but this is wrong behavior and should not be used. Character entities are also problematical, aside from the HTML-significant characters <, &amp; etc. C. Internationalization per HTML 4 Recent versions of the popular browsers have support for some of these features, but at time of writing it seems unwise to rely on this when authoring for a general audience. JAVA SCRIPT Set 1: 1. Whats relationship between JavaScript and ECMAScript? - ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3. 2. What are JavaScript types? - Number, String, Boolean, Function, Object, Null, Undefined. 3. How do you convert numbers between different bases in JavaScript? - Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16); 4. What does isNaN function do? - Return true if the argument is not a number. 5. What is negative infinity? - Its a number in JavaScript, derived by dividing negative number by zero. 6. What boolean operators does JavaScript support? - &&, || and ! 7. What does "1"+2+4 evaluate to? - Since 1 is a string, everything is a string, so the result is 124. 8. How about 2+5+"8"? - Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, its concatenation, so 78 is the result. 9. What looping structures are there in JavaScript? - for, while, do-while loops, but no foreach. 10. How do you create a new object in JavaScript? - var obj = new Object(); or var obj = {}; 11. How do you assign object properties? - obj["age"] = 17 or obj.age = 17. 12. Whats a way to append a value to an array? - arr[arr.length] = value; 13. What is this keyword? - It refers to the current object.

33

Set 2:
1 :: What is JavaScript?
JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. But the language can be--and is--used with other kinds of objects in other environments. For example, Adobe Acrobat Forms uses JavaScript as its underlying scripting language to glue together objects that are unique to the forms generated by Adobe Acrobat. Therefore, it is important to distinguish JavaScript, the language, from the objects it can communicate with in any particular environment. When used for Web documents, the scripts go directly inside the HTML documents and are downloaded to the browser with the rest of the HTML tags and content. JavaScript is a platform-independent, event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.

2 :: Whats relationship between JavaScript and ECMAScript?


ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3.

3 :: How do you submit a form using JavaScript?


Use document.forms[0].submit() (0 refers to the index of the form if we have more than one form in a page, then the first one has the index 0, second has index 1 and so on).

4 :: How to read and write a file using JavaScript?


I/O operations like reading or writing a file is not possible with client-side JavaScript. However , this can be done by coding a Java applet that reads files for the script

5 :: How to detect the operating system on the client machine?


In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used.

6 :: What are JavaScript Data Types?


JavaScript Data Types are Number, String, Boolean, Function, Object, Null, Undefined

7 :: How do you convert numbers between different bases in JavaScript?


Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt (" 3F" , 16)

8 :: How to create arrays in JavaScript?


We can declare an array like this var scripts = new Array() We can add elements to this array like this scripts[0] = " PHP" scripts[1] = " ASP" scripts[2] = " JavaScript"

34
scripts[3] = " HTML" Now our array scripts have 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)

9 :: How do you target a specific frame from a hyperlink in JavaScript?


Include the name of the frame in the target attribute of the hyperlink in JavaScript. < a href=http://www.globalguideline.com target=myframe> Global Guide Line< /a>

10 :: What are a fixed-width table and its advantages in JavaScript?


Fixed width tables are rendered by the browser based on the widths of the columns in the first row, in JavaScript 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 in JavaScript, 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.

11 :: Example of using Regular Expressions for syntax checking in JavaScript?


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. Should be something like: " &a=1&c=4" " ) }

12 :: 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> < form action=" " name=" buttonsGalore" method=" get" > < fieldset style=" margin: 1em text-align: center " > < legend> Select a Hero< /legend> < input type=" button" value=" Agamemnon" onclick=" displayHero(this)" /> < input type=" button" value=" Achilles" onclick=" displayHero(this)" />

35
< input type=" button" value=" Hector" onclick=" displayHero(this)" /> < div style=" height: 1em " />

13 :: Where are cookies actually stored on the hard disk?


This depends on the user's browser and OS. In the case of Netscape with Windows OS, all the cookies are stored in a single file called cookies.txt c:Program FilesNetscapeUsersusernamecookies.txt In the case of IE,each cookie is stored in a separate file namely username@website.txt. c:WindowsCookiesusername@Website.txt

14 :: What can JavaScript programs do?


Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control over the browser like User input validation Simple computations can be performed on the client's machine The user's browser, OS, screen size, etc. can be detected Date and Time Handling

15 :: How to set a HTML document's background color?


document.bgcolor property can be set to any appropriate color.

16 :: How can JavaScript be used to personalize or tailor a Web site to fit individual users?
JavaScript allows a Web page to perform &quot;if-then&quot; kinds of decisions based on browser version, operating system, user input, and, in more recent browsers, details about the screen size in which the browser is running. While a server CGI program can make some of those same kinds of decisions, not everyone has access to or the expertise to create CGI programs. For example, an experienced CGI programmer can examine information about the browser whenever a request for a page is made thus a server so equipped might serve up one page for Navigator users and a different page for Internet Explorer users. Beyond browser and operating system version, a CGI program can't know more about the environment. But a JavaScript-enhanced page can instruct the browser to render only certain content based on the browser, operating system, and even the screen size. Scripting can even go further if the page author desires. For example, the author may include a preference screen that lets the user determine the desired background and text color combination. A script can save this information on the client in a well-regulated local file called a cookie. The next time the user comes to the site, scripts in its pages look to the cookie info and render the page in the color combination selected previously. The server is none the wiser, nor does it have to store any visitorspecific information.

17 :: How is JavaScript different from Java?


JavaScript was developed by Brendan Eich of Netscape Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it's operating in for the user interface, such as a Web document's form elements. JavaScript was initially called LiveScript at Netscape while it was under development. A licensing deal between Netscape and Sun at the last minute let Netscape plug the &quot;Java&quot; name into the name of its scripting language. Programmers use entirely different tools for Java and JavaScript. It is also not uncommon for a programmer of one language to be ignorant of the other. The two languages don't rely on each other and are intended for different purposes. In some ways, the &quot;Java&quot; name on JavaScript has confused the world's understanding of the differences between the two. On the

36
other hand, JavaScript is much easier to learn than Java and can offer a gentle introduction for newcomers who want to graduate to Java and the kinds of applications you can develop with it.

18 :: 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.

19 :: How can JavaScript be used to improve the &quot;look and feel&quot; 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.

20 :: 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 geewhiz versions. But even then, there are plenty of discrepancies between the script ability 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 scripter 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.

37

21 :: What does isNaN function do?


Return true if the argument is not a number.

22 :: What is negative infinity?


Its a number in JavaScript, derived by dividing negative number by zero.

23 :: 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.

24 :: What is the data type of variables of in JavaScript?


All variables are of object type in JavaScript.

25 :: Methods GET and POST in HTML forms - what's the difference?


GET: Parameters are passed in the query string. Maximum amount of data that can be sent via the GET method is limited to about 2kb. POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair.

26 :: How to write a script for "Select" lists using JavaScript?


1. To remove an item from a list set it to null mySelectObject.options[3] = null 2. To truncate a list set its length to the maximum size you desire mySelectObject.length = 2 3. To delete all options in a select object set the length to 0. mySelectObject.leng

27 :: Text From Your Clipboard?


It is true, text you last copied for pasting (copy & paste) can be stolen when you visit web sites using a combination of JavaScript and ASP (or PHP, or CGI) to write your possible sensitive data to a database on another server

28 :: What does the "Access is Denied" IE error mean?


The "Access Denied" error in any browser is due to the following reason. A JavaScript in one window or frame is tries to access another window or frame whose document's domain is different from the document containing the script.

29 :: Is a JavaScript script faster than an ASP script?


Yes. Since JavaScript is a client-side script it does require the web server's help for its computation, so it is always faster than any server-side script like ASP, PHP, etc..

30 :: Are Java and JavaScript the Same?


No. java and JavaScript are two different languages. Java is a powerful object - oriented programming language like C++, C whereas JavaScript is a clientside scripting language with some limitations.

38

31 :: How to embed JavaScript in a web page?


JavaScript code can be embedded in a web page between <script langugage="javascript"> //Place Your JavaScript here. </script> tags

32 :: 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 metaFAQ [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.

33 :: 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, scripter 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 scripter 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 us

34 :: What Boolean operators does JavaScript support?


Boolean operators in JavaScript are as under &&, || and !

35 :: What does "1"+2+4 evaluate to?


Since 1 is a string, everything is a string, so the result is 124.

36 :: What are the ways to emit client-side JavaScript from server-side code in ASP. NET?
The Page object in ASP. NET has two methods that allow emitting of client-side JavaScript: RegisterClientScriptBlock and RegisterStartupScript. Example usage: Page.RegisterClientScriptBlock("ScriptKey", "<script language=javascript>" + "function TestFn() { alert('Clients-side JavaScript'); }</script>"); Page.RegisterStartupScript("ScriptKey", "<script language=javascript>" + "function TestFn() {

39
alert('Clients-side JavaScript'); }</script>"); ScriptKey is used to suppress the same JavaScript from being emitted more than once. Multiple calls to RegisterClientScriptBlock or RegisterStartupScript with the same value of ScriptKey emit the script only once, on the first call.

37 :: What is the difference between RegisterClientScriptBlock and RegisterStartupScript?


RegisterClientScriptBlock emits the JavaScript just after the opening tag. RegisterStartupScript emits the JavaScript at the bottom of the ASP. NET page just before the closing tag.

38 :: What is the difference between a web-garden and a web-farm?


Web-garden - An IIS6.0 feature where you can configure an application pool as a web-garden and also specify the number of worker processes for that pool. It can help improve performance in some cases. Web-farm - a general term referring to a cluster of physically separate machines, each running a webserver for scalability and performance (contrast this with web-garden which refers to multiple processes on one single physical machine).

39 :: How to get the contents of an input box using JavaScript?


Use the "value" property. var myValue = window.document.getElementById("MyTextBox").value;

40 :: How to determine the state of a checkbox using JavaScript?


Determining the state of a checkbox in JavaScript var checkedP = window.document.getElementById("myCheckBox").checked;

41 :: How to set the focus in an element using Javascript?


Setting the focus in an element using JavaScript <script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script>

42 :: 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 JavaScript file to be accessed.

43 :: What is the difference between an alert box and a confirmation box?


An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel.

44 :: What is a prompt box?


A prompt box allows the user to enter input by providing a text box.

40

45 :: Can JavaScript code be broken in different lines?


Breaking is possible within a string statement by using a backslash at the end but not within any other javascript statement. that is , document.write("Hello world"); is possible but not document.write ("hello world");

46 :: Taking a developers perspective, do you think that that JavaScript is easy to learn and use?
One of the reasons JavaScript has the word "script" in it is that as a programming language, the vocabulary of the core language is compact compared to full-fledged programming languages. If you already program in Java or C, you actually have to unlearn some concepts that had been beaten into you. For example, JavaScript is a loosely typed language, which means that a variable doesn't care if it's holding a string, a number, or a reference to an object; the same variable can even change what type of data it holds while a script runs. The other part of JavaScript implementation in browsers that makes it easier to learn is that most of the objects you script are pre-defined for the author, and they largely represent physical things you can see on a page: a text box, an image, and so on. It's easier to say, "OK, these are the things I'm working with and I'll use scripting to make them do such and such," instead of having to dream up the user interface, conceive of and code objects, and handle the interaction between objects and users. With scripting, you tend to write a _lot_ less code.

47 :: 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.

48 :: How about 2+5+"8"?


Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, its concatenation, so 78 is the result.

49 :: What is the difference between SessionState and ViewState?


ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application.

50 :: What does the EnableViewStateMac setting in an aspx page do?


Setting EnableViewStateMac=true is a security measure that allows ASP. NET to ensure that the viewstate for a page has not been tampered with. If on Postback, the ASP. NET framework detects that there has been a change in the value of viewstate that was sent to the browser, it raises an error Validation of viewstate MAC failed. Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute is not specified is also true) in an aspx page.

51 :: What looping structures are there in JavaScript?


JavaScript supports for loop, while loop, do-while loop, but there is no foreach loop in JavaScript. the

41

52 :: To put a "close window" link on a page?


<a href='javascript:window.close()' class='anyCSSClass'> Close </a>

53 :: How to hide JavaScript code from old browsers that don't 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

54 :: How to comment JavaScript code?


Use /* Multiple // start for of line a single Multiple line comments in lines comment comments in JavaScript and in JavaScript JavaScript

*/ for block comments in JavaScript

55 :: Name the numeric constants representing max, min values?


Number.MAX_VALUE Number.MIN_VALUE

56 :: What does JavaScript null mean?


The null value is a unique value representing no value or It implies no object, or null string, no valid Boolean value, no number and no array object. no object.

57 :: How do you create a new object in JavaScript?


Create var //or var obj = {}; a obj new = object new in JavaScript Object();

58 :: How do you assign object properties?


obj["age"] = 17; //or obj.age = 17;

59 :: Whats a way to append a value to an array?


Way to append a value to an array in JavaScript

arr[arr.length] = value;

60 :: What is this keyword?


In JavaScript this keywork refers to the current object.

42

61 :: 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.

62 :: 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 view state MAC failed. What could be one reason that is causing this error?
The most common reason for this error is that the the machine key value in machine.config is different for each server. As a result, view state 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 machine key.

63 :: To set all checkboxes to true using JavaScript?


//select all function var checkboxes = for(i=0;i<checkboxes.length;i++) if(checkboxes.item(i).attributes["type"].value checkboxes.item(i).checked } } } input tags SelectAll() { document.getElementsByTagName("input"); { == "checkbox") { = true;

64 :: How to select an element by id and swapping an image?


<script language="JavaScript" type="text/javascript" > function setBeerIcon() { var beerIcon = document.getElementById("beerIcon"); beerIcon.src = "images/"+getSelectValue("beer")+".jpg"; } </script> <img border="0" src="" id="brandIcon" alt="brand" /> <select name="beer" id="beer" onChange="setButton();setBeerIcon();"> <option value="--Select--">Select beer</option> <option value="heineken">heineken</option> <option value="sol">sol</option> <option value="amstellight">amstellight</option> <option value="coronalight">coronalight</option> <option value="coronaextra">coronaextra</option> <option value=""></option> </select>

43

65 :: What does undefined value mean in JavaScript?


Undefined value means the variable used in the code doesn't exist or is not assigned any value or the property doesn't exist

66 :: What is the difference between undefined value and null value?


(i) Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null (ii) typeof undefined variable or property returns undefined whereas typeof null value returns object

67 :: What is variable typing in JavaScript?


It is perfectly legal to assign a number to a variable and then assign a string to the same variable as follows example i = 10; i = "string"; This is called variable typing

68 :: Does JavaScript have the concept level scope?


No. Javascript does not have block level scope, all the variables declared inside a function possess the same level of scope unlike c, c++, java.

69 :: What are undefined and undeclared variables?


Undeclared variables are those that are not declared in the program (do not exist at all), trying to read their values gives runtime error. But if undeclared variables are assigned then implicit declaration is done . 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.

70 :: What is === operator?


In JavaScript === is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion.

71 :: 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

72 :: How to find radio button selection when a form is submitted?


<script function var findButton() = type="text/javascript"> { document.forms.animalForm;

myForm

44
var i; for(i=0;i<myForm.marsupial.length; i++) { if(myForm.marsupial[i].checked) { break; } } alert("You selected ""+myForm.marsupial[i].value+""."); } </script> <form name="animalForm" action=""> <input type="radio" name="marsupial" value="kangaroo" />Kangaroo <br /><input type="radio" name="marsupial" value="Opossum" />Opossum <br /><input type="radio" name="marsupial" value="Tasmanian Tiger" />Tasmanian Tiger <input type="button" name="GO" value="GO" onclick="findButton()" />

73 :: How to disable an HTML object?


To disable an HTML object in JavaScript use below line of code...

document.getElementById("myObject").disabled = true;

74 :: To write messages to the screen without using "document.write()"?


Changing the contents of an element is a much better solution. When the method showStatus is invoked it will change the content of the span. function var element element.textContent = element.innerHTML = message; return } <span id="mystatus">Test. </span> showStatus(message) { = document.getElementById("mystatus"); message; //for Firefox //for IE (why can't we all just get along?) true;

75 :: How to Add new elements dynamically?


<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Title of page</title> <script type="text/javascript"> function addNode() { var newP = document.createElement("p"); var textNode = document.createTextNode(" I'm a new text node"); newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP); } </script> </head> <body onload="addNode();" style=" background: url('../images/Sand-1280.jpg'); background-color: yellow;"> <p id="firstP">firstP<p> </body> </html>

45

76 :: How to have an element invoke a JavaScript on selection, instead of going to a new URL?
<script function pseudoHitMe() alert("Ouch!"); } </script> <a href="javascript:pseudoHitMe()">hit me</a> type="text/javascript"> {

77 :: How to have the status line update when the mouse goes over a link (The support of the status line is sporadic)?
<a onmouseover="window.status='Hi onmouseout="window.status='';return There!';return at the href="javascript.shtml" true" Status bar</a>

true">Look

Look at the Status bar as your cursor goes over the link.

78 :: Explain unescape() and escape() in JavaScript?


These are similar to the decodeURI() and encodeURI(), but escape() is used for only portions of a URI. <script var myvalue document.write("Original document.write("<br document.write("<br </script> = />uri "Sir myvalue: />escaped: part: type="text/javascript"> Robbert Scott"; "+myvalue); "+escape(myvalue)); "&author="+escape(myvalue)+"""); bad things happen. type="text/javascript"> Web Tutorials" "+uri); "+escape(uri));

If you use escape() for the whole URI... well <script var uri = "http://www.google.com/search?q=Online document.write("Original uri: document.write(" escaped: </script>

79 :: How to create a popup warning box?


Below line will help us how to create a popup warning box in JavaScript....

alert('Warning: Please enter an integer between 0 and 100.');

80 :: How to create a confirmation box?


Below line will help us how to create a Confirmation box in JavaScript....

confirm("Do you really want to launch the missile today. HuM?");

81 :: How to create an input box?


Below line will help us how to create a Input box in JavaScript....

prompt("What is your name?");

46

82 :: How to open a window with no toolbar, but with the location object?
window.open ( "http://www.globalguideline.com", "Online "resizable=yes, "status=yes," "toolbar=yes," "location=yes," "menubar=yes," "scrollbars=yes," "width=800," "height=400" );

Web "

Tutorials", + + + + + + +

83 :: How to setting a cookie with the contents of a textbox?


Values stored in cookies may not have semicolons, commas, or spaces. You should use the handy "escape()" function to encode the values, and "unescape()" to retrieve them. //Sets cookie function var myBox document.cookie = } current value for myTextBox TextBoxOnchange() { = window.document.getElementById(myTextBox"); "myTextBox="+ escape(myBox.value) + getExpirationString(); ";expires=Thu, 5 Jan 2006 16:07:52 UTC" getExpirationString() { = new Date(); = exp.getTime()+(120*24*60*60*1000); ";expires="+exp.toGMTString(); the event handler type="text" in the HTML. of

//return a string like function var exp var threemonths exp.setTime(threemonths); return } This is called from

<input name="myTextBox" onchange="javascript:TextBoxOnchange()" />

id="myTextBox"

84 :: How to getting values from cookies to set widgets?


function //from var // var var var var while var if cEnd if cEnd getCookieData(labelName) Danny = property only once = = = < i == == = { Goodman labelName.length; for speed document.cookie; cookieData.length; 0; cEnd; cLen) { + labelLen; labelName) { cookieData.indexOf(";",j); -1) { cookieData.length;

read

labelLen cookie cookieData cLen i

(i j = (cookieData.substring(i,j) = (cEnd

47
} return } i++; } return } //init() is called function setValueFromCookie("brand"); setValueFromCookie("market"); setValueFromCookie("measure"); }

unescape(cookieData.substring(j+1,

cEnd));

""; from the init() body tag onload function. {

function setValueFromCookie(widget) if( getCookieData(widget) != document.getElementById(widget).value = } }

{ "") { getCookieData(widget);

//if you name your cookies the widget ID, you can use the following helper function function setCookie(widget) { document.cookie = widget + "=" + escape(document.getElementById(widget).value) + getExpirationString(); }

85 :: How to Handle Event Handlers?


You can add an event handler <script function alert("I've } // </script> <input type="button" id="hitme" in the HTML hitme() been definition of the element like this, type="text/javascript"><!-{ hit!"); --> name="hitme" value="hit me" onclick="hitme()"

Or, interestingly enough you can just assign the event's name on the object directly with a reference to the method you want to assign. <input type="button" id="hitme2" <script function alert("I've been } document.getElementById("hitme2").onclick // </script> You can also use an = name="hitme2" hitme2() hit = value="hit me2"/> type="text/javascript"><!-{ too!"); hitme2; --> method () { like alert("howdy!"); this: }

anonymous function

document.getElementById("hitme3").onclick

You can also use the the W3C addEvventListener() method, but it does not work in IE yet:

48
<input <script function alert("I've } type="button" id="hitme4" been name="hitme4" hitme4() hit value="hit me4"/> type="text/javascript"><!-{ four!");

86 :: How to remove the event listener?


<script document.getElementById("hitme4").removeEventListener("click", </script> Key type="text/javascript"> hitme4, false); Events

"onkeydown", "onkeypress", "onkeyup" events are supported both in ie and standards-based browsers. <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>

87 :: How to change style on an element?


Between CSS and JavaScript is a weird symmetry. CSS style rules are laid on top of the DOM. The CSS property names like "font-weight" are transliterated into "myElement.style.fontWeight". The class of an element can be swapped out. For example: document.getElementById("myText").style.color = "green"; document.getElementById("myText").style.fontSize = "20"; -ordocument.getElementById("myText").className = "regular";

88 :: How to make elements invisible?


Change the "visibility" attribute of the style object associated with your element. Remember that a hidden element still takes up space, use "display" to make the space disappear as well. if ( myElement.style.visibility } myElement.style.visibility } x else = == = y) { 'visible'; { 'hidden';

49

89 :: How to set the cursor to wait?


In theory, we should cache the current state of the cursor and then put it back to its original state. document.body.style.cursor = 'wait'; //do something interesting and time consuming document.body.style.cursor = 'auto';

90 :: How to reload the current page?


To reload the current web page using JavaScript use the below line of code...

window.location.reload(true);

91 :: How to force a page to go to another page using JavaScript?


<script <!-language="JavaScript" type="text/javascript" >

location.href="http://www.globalguideline.com"; //--> </script>

92 :: How to convert a string to a number using JavaScript?


We can use the parseInt() and parseFloat() methods in JavaScript to convert a string to a number or numeric value. Notice that extra letters following a valid number are ignored, which is kinda wierd but convenient at times. parseInt("100") ==> parseFloat("98.6") ==> parseFloat("98.6 is a common temperature.") parseInt("aa") ==> Nan //Not parseInt("aa",16) ==> 170 //We can supply a radix or base 100 98.6 98.6 Number

==> a

93 :: How to convert numbers to strings using JavaScript?


We var //or var We var var can mystring specify a myinteger mystring = base = for = the myinteger.toString(); conversion, 14; myinteger.toString(16); can prepend the number with an = empty string in JavaScript ""+myinteger;

mystring

mystring will be "e".

94 :: How to test for bad numbers using JavaScript?


The global method, "isNaN()" can tell us about value if a number has gone bad in JavaScript. var temperature = parseFloat(myTemperatureWidget.value); {

if(!isNaN(temperature))

50
alert("Please } enter a valid temperature.");

95 :: What's Math Constants and Functions using JavaScript?


The Math.PI, Math Math also object has a contains zillion useful helpful constants functions in such as Math.E

JavaScript. value largest and 1

Math.abs(value); //absolute Math.max(value1, value2); //find the Math.random() //generate a decimal number between Math.floor(Math.random()*101) //generate a decimal number between 0 and 100

96 :: What's the Date object using JavaScript?


Time inside a date object is stored as milliseconds since Jan 1, 1970 in JavaScript. e.g. new Date(06,01,02) // produces "Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)" new Date(06,01,02).toLocaleString() // produces "Friday, February 02, 1906 00:00:00" new Date(06,01,02) - new Date(06,01,01) // produces "86400000"

97 :: What does the delete operator do?


The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with var keyword.

98 :: How to delete an array entry using JavaScript?


The "delete" operator removes an array element in JavaScript , but oddly does not change the size of the array. <script var days = ["Sunday","Monday","Tuesday","Wednesday", document.write("Number of days:"+days.length); document.write("<br />Number of </script> This Number Number of days:7 of type="text/javascript"> "Thursday","Friday","Saturday"]; delete days[4]; days:"+days.length); produces days:7

99 :: How to use strings as array indexes using JavaScript?


JavaScript does not have a true hashtable object, but through its wierdness, you can use the array as a hashtable. <script var days for(var days[days[i]] } = ["Sunday","Monday","Tuesday","Wednesday", i=0; i < = type="text/javascript"> "Thursday","Friday","Saturday"]; i++) { days[i];

days.length;

document.write("days["Monday"]:"+days["Monday"]);

51
</script> This days["Monday"]:Monday produces

100 :: How to use "join()" to create a string from an array using JavaScript?
"join" concatenates the array elements with a specified separator between them in JavaScript. <script var days = ["Sunday","Monday","Tuesday","Wednesday", document.write("days:"+days.join(",")); </script> This days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday type="text/javascript"> "Thursday","Friday","Saturday"];

produces

101 :: How to make a array as a stack using JavaScript?


The pop() and push() functions turn a harmless array "two", into a stack in JavaScript...

<script var numbers = numbers.push("five"); numbers.push("six"); document.write(numbers.pop()); document.write(numbers.pop()); document.write(numbers.pop()); </script> This sixfivefour

["one",

type="text/javascript"> "three", "four"];

produces

102 :: How to shift and unshift using JavaScript?


<script var numbers numbers.unshift("zero"); document.write(" document.write(" document.write(" </script> = ["one", "two", type="text/javascript"> "three", "four"]; "+numbers.shift()); "+numbers.shift()); "+numbers.shift());

This produces zero one two shift, unshift, push, and pop may be used on the same array in JavaScript. Queues are easily implemented using combinations.

103 :: How to create an object using JavaScript?


Objects can be created in many ways. One way is to create the object and add the fields directly. <script type="text/javascript"> var myMovie = new Object(); myMovie.title = "Aliens"; myMovie.director = "James Cameron"; document.write("movie: title ""+myMovie.title+"""); <

52
This produces movie: title "Aliens" To create an object write a method with the name of 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] 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]

104 :: How to associate functions with objects using JavaScript?


Now create a custom "toString()" method for our movie object. We can embed the function directly in the object like this. <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 parenthisis, 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; }

53
var aliens document.write(aliens.toString()); </script> This title: Aliens director: Cameron = new movie("Aliens","Cameron"); produces

105 :: What is eval() in JavaScript?


The eval() method is incredibly powerful allowing us to execute snippets of code during execution in JavaScript. <script var USA_Texas_Austin document.write("Population is </script> type="text/javascript"> = "521,289"; "+eval("USA_"+"Texas_"+"Austin"));

106 :: What does break and continue statements do in JavaScript?


Continue statement continues the current loop (if label not specified) in a new iteration whereas break statement exits the current loop in JavaScript.

107 :: How to create a function using function constructor?


The following example illustrates this It creates a function called square with argument x and returns x multiplied by itself. var square = new Function ("x","return x*x");

108 :: What's Prototypes for JavaScript?


Objects have "prototypes" from which they may inherit fields and functions.

<script type="text/javascript"> function movieToString() { return("title: "+this.title+" director: "+this.director); } function movie(title, director) { this.title = title; this.director = director || "unknown"; //if null assign to "unknown" this.toString = movieToString; //assign function to this method pointer } movie.prototype.isComedy = false; //add a field to the movie's prototype var officeSpace = new movie("OfficeSpace"); var narnia = new movie("Narni","Andrew Adamson"); document.write(narnia.toString()); document.write(" Narnia a comedy? "+narnia.isComedy); officeSpace.isComedy = true; //override the default just for this object document.write(" Office Space a comedy? "+officeSpace.isComedy); </script>

109 :: What are decodeURI() and encodeURI() functions in JavaScript?


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">

54
var uri = "http://www.google.com/search?q=Online Web Tutorials at GlobalGuideLine" document.write("Original uri: "+uri); document.write("<br />encoded: "+encodeURI(uri)); </script>

Set 3:
JavaScript Interview Questions
1) Explain in brief about Java script? Java Script, originally supported by netscape navigator, is the most popular web scripting language. Java Script lets you embed programs right in your web pages and run these programs using the web browser. With the introduction of dynamic html necessity of Java Script is becoming more of a necessity. 2) Explain about the structured programming features of Java Script? Java script supports most of the structured programming syntax present in C language. It doesnt support scoping which is present in C programming in block style. It also supports various forms and methods of testing the type of an object which also includes the famous duck type testing. 3) Explain about inner functions and closures present in Function level programming? Each time the outer function is invoked an inner function is created. Variables for the outer function still continue to exist as long as the inner function exists. This process continues until invocation exists. This is the how closures work within the JavaScript with all its functionalities. 4) Explain functions as object constructors? If you prefix a new with a function call creates a new object and you can call that functions with a local keyword which is attached to that object. Object prototype property determines the functions prototype property. These functions act as object constructors along with their normal properties. 5) Explain functions as methods? There is no big distinction between function definition and method definition. The only difference occurs when you actually call that function as a method which inturn is attached to an object. When the function is called in this manner its local keyword is bound to that object. 6) Explain about run time environment of Javascript? Java script does not have a sophisticated run time of its own but it relies on the web browser of the client. It relies on this run time environment for its functions and methods to perform their duties by which scripts can interact with the user. 7) Explain about Variadic functions? When you use variadic function in Javascript, an indefinite number of parameters can be passed onto the function. Inturn the function can access the parameters through formal parameters and local arguments. Variadic functions are much successful when you need to assign different number of parameters to functions. 8) State some simple usages with Javascript? Some of the simple usages with Javascript are 1) A new pop up window can be made and changed according to the requirements such as no menus, scroll bars, etc. 2) Validation of input values submitted by the user through a web form. 3) Mouse over effects, scroll effects etc which can be changed by the scroll of the mouse pointer over a certain image, etc. 9) What is a JavaScript engine?

55
Java Script engine was first created by Netscape navigator. This engine interrupts the java script code and executes accordingly. The most common Java Script user interface is the web browser. Java script engine was created by Brendan. 10) Explain about the security functions presents in JavaScript? As JavaScript uses Web as an interface it gives an ample scope for users to transfer malicious scripts. Most of the JavaScript related breaches and wrong doings are due to sandbox or same origin policy. 11) What are the precautions taken by the web browsers to contain malicious activity with Java Script? Java script activities are restricted by web browsers in two ways they are. 1) First scripts run in sandbox which performs the most basic functions such as executing or running the code or script. This doesnt allow programming activities. 2) Scripts present in one site cannot have access to other sites; this is done with the help of same origin policy. 12) What are the rare cases when Java Script will not function? These are the following cases when Java Script will not function. 1) An old browser which doesnt support DOM. 2) PDA or Mobile Phone will not execute Java Script. 3) Security reasons will not allow optimal performance of Jscript. 4) Speech browsers will not allow the functioning of Jscript. 13) Explain about Cross site scripting? Cross site scripting raises security threats during execution and secured data transfer through web sites. It uses same origin policy. When a malicious script is made to run it discloses private information to the wrong person. This occurs because some one clicks on the request sent by the wrong doer. 14) Explain about arrays in Java Script? Array maps everything from an integer to Values. Objects map everything from values to integers, Javascript specialize in certain special functions through which they can include integer indicies in their behavior. Large indicies can be removed if the length of the array specified is very small. 15) Explain about defining numbers in Java Script? Java Script represents numbers in the form of IEEE-754 doubles. This form of representation provides accuracy upto 14-15 significant digits. They represent fractions but not the decimal numbers to an extent. To perform explicit numeric conversion you can use Number constructor. 16) Explain about strings in JavaScript? Strings are represented as a sequence of characters in Javascript. Strings can be created when you place characters between double quotations or single quotations. Individual characters can be accessed by arrays. 17) Explain about the Boolean functions present in Javascript? Three Boolean operators are present in Javascript they are 1) && 2) II 3) / All the operators are regarded as true unless the Javascript regards them as false. You can define these operators to make as statement false number0, null, undefined, or a string of length 0, etc. Boolean function performs these conversions explicitly.

Set 4:

56

What is JavaScript?
A1: JavaScript is a general-purpose programming language designed to let programmers of all skill levels control the behavior of software objects. The language is used most widely today in Web browsers whose software objects tend to represent a variety of HTML elements in a document and the document itself. But the language can be--and is--used with other kinds of objects in other environments. For example, Adobe Acrobat Forms uses JavaScript as its underlying scripting language to glue together objects that are unique to the forms generated by Adobe Acrobat. Therefore, it is important to distinguish JavaScript, the language, from the objects it can communicate with in any particular environment. When used for Web documents, the scripts go directly inside the HTML documents and are downloaded to the browser with the rest of the HTML tags and content. A2:JavaScript is a platform-independent,event-driven, interpreted client-side scripting and programming language developed by Netscape Communications Corp. and Sun Microsystems.
How is JavaScript different from Java? JavaScript was developed by Brendan Eich of Netscape; Java was developed at Sun Microsystems. While the two languages share some common syntax, they were developed independently of each other and for different audiences. Java is a full-fledged programming language tailored for network computing; it includes hundreds of its own objects, including objects for creating user interfaces that appear in Java applets (in Web browsers) or standalone Java applications. In contrast, JavaScript relies on whatever environment it's operating in for the user interface, such as a Web document's form elements. JavaScript was initially called LiveScript at Netscape while it was under development. A licensing deal between Netscape and Sun at the last minute let Netscape plug the "Java" name into the name of its scripting language. Programmers use entirely different tools for Java and JavaScript. It is also not uncommon for a programmer of one language to be ignorant of the other. The two languages don't rely on each other and are intended for different purposes. In some ways, the "Java" name on JavaScript has confused the world's understanding of the differences between the two. On the other hand, JavaScript is much easier to learn than Java and can offer a gentle introduction for newcomers who want to graduate to Java and the kinds of applications you can develop with it. Whats relationship between JavaScript and ECMAScript? ECMAScript is yet another name for JavaScript (other names include LiveScript). The current JavaScript that you see supported in browsers is ECMAScript revision 3. How do you submit a form using Javascript? Use document.forms[0].submit(); (0 refers to the index of the form if you have more than one form in a page, then the first one has the index 0, second has index 1 and so on). How do we get JavaScript onto a web page? You can use several different methods of placing javascript in you pages. You can directly add a script element inside the body of page. 1. For example, to add the "last updated line" to your pages, In your page text, add the following: <p>blah, blah, blah, blah, blah.</p> <script type="text/javascript" > <!-- Hiding from old browsers

57
document.write("Last Updated:" + document.lastModified); document.close(); // --> </script> <p>yada, yada, yada.</p>

(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> Javascript can be referenced from a separate file Javascript may also a placed in a separate file on the server and referenced from an HTML page. (Don't use the shorthand ending "<script ... />). These are typically placed in the <head> element. <script type="text/javascript" SRC="myStuff.js"></script>
How to read and write a file using javascript? I/O operations like reading or writing a file is not possible with client-side javascript. However , this can be done by coding a Java applet that reads files for the script. How to detect the operating system on the client machine? In order to detect the operating system on the client machine, the navigator.appVersion string (property) should be used. 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

58
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 plugins 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. What are JavaScript types? Number, String, Boolean, Function, Object, Null, Undefined. How do you convert numbers between different bases in JavaScript? Use the parseInt() function, that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16); How to create arrays in JavaScript? We can declare an array like this var scripts = new Array(); We can add elements to this array like this

scripts[0] scripts[1] scripts[2] scripts[3]

= = = =

"PHP"; "ASP"; "JavaScript"; "HTML";

Now our array scrips has 4 elements inside it and we can print or access them by using

59
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);
How do you target a specific frame from a hyperlink? Include the name of the frame in the target attribute of the hyperlink. <a href=mypage.htm target=myframe>>My Page</a> What is a fixed-width table and its advantages?

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 tablelayout: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. Example of using Regular Expressions for syntax checking in JavaScript ... 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\"");

}
Where are cookies actually stored on the hard disk? This depends on the user's browser and OS. In the case of Netscape with Windows OS,all the cookies are stored in a single file called

cookies.txt c:\Program Files\Netscape\Users\username\cookies.txt In the case of IE,each cookie is stored in a separate file namely username@website.txt. c:\Windows\Cookies\username@Website.txt
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!" />

60
<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> <form action="" name="buttonsGalore" method="get"> <fieldset style="margin: 1em; text-align: center;"> <legend>Select a Hero</legend> <input type="button" value="Agamemnon" onclick="displayHero(this)" /> <input type="button" value="Achilles" onclick="displayHero(this)" /> <input type="button" value="Hector" onclick="displayHero(this)" /> <div style="height: 1em;" /> </fieldset> </form>
What can javascript programs do? Generation of HTML pages on-the-fly without accessing the Web server. The user can be given control over the browser like User input validation Simple computations can be performed on the client's machine The user's browser, OS, screen size, etc. can be detected Date and Time Handling How to set a HTML document's background color? document.bgcolor property can be set to any appropriate color. How can JavaScript be used to personalize or tailor a Web site to fit individual users? JavaScript allows a Web page to perform "if-then" kinds of decisions based on browser version, operating system, user input, and, in more recent browsers, details about the screen size in which the browser is running. While a server CGI program can make some of those same kinds of decisions, not everyone has access to or the expertise to create CGI programs. For example, an experienced CGI programmer can examine information about the browser whenever a request for a page is made; thus a server so equipped might serve up one page for Navigator users and a different page for Internet Explorer users. Beyond browser and operating system version, a CGI program can't know more about the environment. But a JavaScript-enhanced page can instruct the browser to render only certain content based on the browser, operating system, and even the screen size. Scripting can even go further if the page author desires. For example, the author may include a preference screen that lets the user determine the desired background and text color combination. A script can save this information on the client in a well-regulated local file called a cookie. The next time the user comes to the site, scripts in its pages look to the cookie info and render the page in the color combination selected previously. The server is none the wiser, nor does it have to store any visitor-specific information. 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

61
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.
What does isNaN function do? Return true if the argument is not a number. What is negative infinity? Its a number in JavaScript, derived by dividing negative number by zero. 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 is the data type of variables of in JavaScript? All variables are of object type in JavaScript. Methods GET and POST in HTML forms - what's the difference? GET: Parameters are passed in the querystring. Maximum amount of data that can be sent via the GET method is limited to about 2kb. POST: Parameters are passed in the request body. There is no limit to the amount of data that can be transferred using POST. However, there are limits on the maximum amount of data that can be transferred in one name/value pair. How to write a script for "Select" lists using javascript 1. To remove an item from a list set it to null mySelectObject.options[3] = null; 2. To truncate a list set its length to the maximum size you desire mySelectObject.length = 2; 3. To delete all options in a select object set the length to 0. mySelectObject.leng Text From Your Clipboard? It is true, text you last copied for pasting (copy & paste) can be stolen when you visit web sites using a combination of JavaScript and ASP (or PHP, or CGI) to write your possible sensitive data to a database on another server. What does the "Access is Denied" IE error mean? The "Access Denied" error in any browser is due to the following reason. A javascript in one window or frame is tries to access another window or frame whose document's domain is different from the document containing the script.

62
Is a javascript script faster than an ASP script? Yes.Since javascript is a client-side script it does require the web server's help for its computation,so it is always faster than any server-side script like ASP,PHP,etc.. Are Java and JavaScript the Same? No.java and javascript are two different languages. Java is a powerful object - oriented programming language like C++,C whereas Javascript is a client-side scripting language with some limitations. How to embed javascript in a web page? javascript code can be embedded in a web page between <script langugage="javascript"></script> tags 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. What Boolean operators does JavaScript support? &&, || and ! What does "1"+2+4 evaluate to? Since 1 is a string, everything is a string, so the result is 124.

63
What is the difference between a web-garden and a web-farm? Web-garden - An IIS6.0 feature where you can configure an application pool as a webgarden and also specify the number of worker processes for that pool. It can help improve performance in some cases. Web-farm - a general term referring to a cluster of physically separate machines, each running a web-server for scalability and performance (contrast this with web-garden which refers to multiple processes on one single physical machine). How to get the contents of an input box using Javascript? Use the "value" property. var myValue = window.document.getElementById("MyTextBox").value; How to determine the state of a checkbox using Javascript? var checkedP = window.document.getElementById("myCheckBox").checked; How to set the focus in an element using Javascript? <script> function setFocus() { if(focusElement != null) { document.forms[0].elements["myelementname"].focus(); } } </script> 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 is the difference between an alert box and a confirmation box? An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel. What is a prompt box? A prompt box allows the user to enter input by providing a text box. Can javascript code be broken in different lines? Breaking is possible within a string statement by using a backslash \ at the end but not within any other javascript statement. that is , document.write("Hello \ world"); is possible but not document.write \ ("hello world"); Taking a developers perspective, do you think that that JavaScript is easy to learn and use? One of the reasons JavaScript has the word "script" in it is that as a programming language, the vocabulary of the core language is compact compared to full-fledged programming languages. If you already program in Java or C, you actually have to unlearn some concepts that had been beaten into you. For example, JavaScript is a loosely typed language, which means that a variable doesn't care if it's holding a string, a number, or a reference to an object; the same variable can even change what type of data it holds while a script runs. The other part of JavaScript implementation in browsers that makes it easier to learn is that most of the objects you script are pre-defined for the author, and they largely

64
represent physical things you can see on a page: a text box, an image, and so on. It's easier to say, "OK, these are the things I'm working with and I'll use scripting to make them do such and such," instead of having to dream up the user interface, conceive of and code objects, and handle the interaction between objects and users. With scripting, you tend to write a _lot_ less code.
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 about 2+5+"8"? Since 2 and 5 are integers, this is number arithmetic, since 8 is a string, its concatenation, so 78 is the result. What is the difference between SessionState and ViewState? ViewState is specific to a page in a session. Session state refers to user specific data that can be accessed across all pages in the web application. What does the EnableViewStateMac setting in an aspx page do? Setting EnableViewStateMac=true is a security measure that allows ASP.NET to ensure that the viewstate for a page has not been tampered with. If on Postback, the ASP.NET framework detects that there has been a change in the value of viewstate that was sent to the browser, it raises an error - Validation of viewstate MAC failed. Use <%@ Page EnableViewStateMac="true"%> to set it to true (the default value, if this attribute is not specified is also true) in an aspx page. How to Accessing Elements using javascript? To do something interesting with HTML elements, we must first be able to uniquely identify which element we want. In the example <body> <form action=""> <input type="button" id="useless" name="mybutton" value="doNothing" /> </form> </body>

We can use the "getElementById" method (which is generally preferred) document.getElementById("useless").style.color = "red"; or we can use the older hierarchical navigation method, document.forms[0].mybutton.style.color = "blue"; Notice that this uses the "name" attribute of the element to locate it. # Example of Accessing Elements in a DOM. <script type="text/javascript" > function showStatus() { var selectWidget = document.forms.beerForm.elements["beer"]; var myValue = selectWidget.options[selectWidget.selectedIndex].value; alert('You drank a \"'+ myValue +"\""); return true;

65
</script> <form name="beerForm" action=""> <select name="beer"> <option selected="selected">Select Beer</option> <option>Heineken</option> <option>Amstel Light</option> <option>Corona</option> <option>Corona Light</option> <option>Tecate</option> </select> <input type="button" name="submitbutton" value="Drink" onclick="showStatus()" /> </form>
What looping structures are there in JavaScript? for, while, do-while loops, but no foreach. To put a "close window" link on a page ? <a href='javascript:window.close()' class='mainnav'> Close </a> 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 /*

*/ for block comments


Name the numeric constants representing max,min values Number.MAX_VALUE Number.MIN_VALUE What does javascript null mean? The null value is a unique value representing no value or no object. It implies no object,or null string,no valid boolean value,no number and no array object. How do you create a new object in JavaScript? var obj = new Object(); or var obj = {}; How do you assign object properties? obj["age"] = 17 or obj.age = 17. Whats a way to append a value to an array? arr[arr.length] = value;

66
What is this keyword? It refers to the current object. 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 webfarms 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. To set all checkboxes to true using JavaScript? //select all input tags function SelectAll() { var checkboxes = document.getElementsByTagName("input"); for(i=0;i<checkboxes.length;i++) { if(checkboxes.item(i).attributes["type"].value == "checkbox") { checkboxes.item(i).checked = true;

} } }
How to select an element by id and swapping an image ? ... <script language="JavaScript" type="text/javascript" > function setBeerIcon() {

var beerIcon = document.getElementById("beerIcon"); beerIcon.src = "images/"+getSelectValue("beer")+".jpg";

}
</script> ... <img border="0" src="" id="brandIcon" alt="brand" /> <select name="beer" id="beer" onChange="setButton();setBeerIcon();"> <option value="--Select--">Select beer</option> <option value="heineken">heineken</option> <option value="sol">sol</option> <option value="amstellight">amstellight</option>

67
<option value="coronalight">coronalight</option> <option value="coronaextra">coronaextra</option> <option value=""></option> </select>
What does undefined value mean in javascript? Undefined value means the variable used in the code doesn't exist or is not assigned any value or the property doesn't exist. What is the difference between undefined value and null value? (i)Undefined value cannot be explicitly stated that is there is no keyword called undefined whereas null value has keyword called null (ii)typeof undefined variable or property returns undefined whereas typeof null value returns object What is variable typing in javascript? It is perfectly legal to assign a number to a variable and then assign a string to the same variable as follows example i = 10; i = "string"; This is called variable typing Does javascript have the concept level scope? No. JavaScript does not have block level scope, all the variables declared inside a function possess the same level of scope unlike c,c++,java. What are undefined and undeclared variables? Undeclared variables are those that are not declared in the program (do not exist at all),trying to read their values gives runtime error.But if undeclared variables are assigned then implicit declaration is done . 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. What is === operator ? ==== is strict equality operator ,it returns true only when the two operands are having the same value without any type conversion. 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

68
How to find radio button selection when a form is submitted? <script type="text/javascript"> function findButton() { var myForm = document.forms.animalForm; var i; for(i=0;i<myForm.marsupial.length; i++) { if(myForm.marsupial[i].checked) { break;

} }
alert("You selected \""+myForm.marsupial[i].value+"\".");

}
</script> <form name="animalForm" action=""> <input type="radio" name="marsupial" value="kangaroo" />Kangaroo <br /><input type="radio" name="marsupial" value="Opossum" />Opossum <br /><input type="radio" name="marsupial" value="Tasmanian Tiger" />Tasmanian Tiger <input type="button" name="GO" value="GO" onclick="findButton()" />
How to disable an HTML object ? document.getElementById("myObject").disabled = true; To write messages to the screen without using "document.write()" ? Changing the contents of an element is a much better solution. When the method showStatus is invoked it will change the content of the span. ... function showStatus(message) { var element = document.getElementById("mystatus"); element.textContent = message; //for Firefox element.innerHTML = message; //for IE (why can't we all just get along?) return true;

}
... <span id="mystatus">Test. </span> ...
How to Add new elements dynamically ? <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>t1</title> <script type="text/javascript"> function addNode() { var newP = document.createElement("p"); var textNode = document.createTextNode(" I'm a new text node"); newP.appendChild(textNode); document.getElementById("firstP").appendChild(newP);

}
</script> </head>

69

<body onload="addNode();" style=" background: url('../images/Sand-1280.jpg'); background-color: yellow;"> <p id="firstP">firstP<p> </body> </html>
How to have an element invoke a javascript on selection, instead of going to a new URL: ? <script type="text/javascript"> function pseudoHitMe() { alert("Ouch!");

}
</script> <a href="javascript:pseudoHitMe()">hit me</a>
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. How to create a popup warning box alert('Warning: Please enter an integer between 0 and 100.'); How to create a confirmation box? confirm("Do you really want to launch the missile?"); How to create an input box? prompt("What is your temperature?"); How to setting a cookie with the contents of a textbox ? Values stored in cookies may not have semicolons, commas, or spaces. You should use the handy "escape()" function to encode the values, and "unescape()" to retrieve them.

//Sets cookie of current value for myTextBox function TextBoxOnchange() { var myBox = window.document.getElementById(myTextBox"); document.cookie = "myTextBox="+ escape(myBox.value) + getExpirationString();

}
//return a string like ";expires=Thu, 5 Jan 2006 16:07:52 UTC" function getExpirationString() { var exp = new Date(); var threemonths = exp.getTime()+(120*24*60*60*1000); exp.setTime(threemonths); return ";expires="+exp.toGMTString();

70

This is called from the event handler in the HTML. <input name="myTextBox" type="text" id="myTextBox" onchange="javascript:TextBoxOnchange()" />
How to getting values from cookies to set widgets? function getCookieData(labelName) { //from Danny Goodman var labelLen = labelName.length; // read cookie property only once for speed var cookieData = document.cookie; var cLen = cookieData.length; var i = 0; var cEnd; while (i < cLen) { var j = i + labelLen; if (cookieData.substring(i,j) == labelName) { cEnd = cookieData.indexOf(";",j); if (cEnd == -1) { cEnd = cookieData.length;

}
return unescape(cookieData.substring(j+1, cEnd));

}
i++;

}
return "";

}
//init() is called from the body tag onload function. function init() { setValueFromCookie("brand"); setValueFromCookie("market"); setValueFromCookie("measure");

}
function setValueFromCookie(widget) { if( getCookieData(widget) != "") { document.getElementById(widget).value = getCookieData(widget);

} }
//if you name your cookies the widget ID, you can use the following helper function function setCookie(widget) { document.cookie = widget + "=" + escape(document.getElementById(widget).value) + getExpirationString();

}
How to change style on an element? Between CSS and javascript is a weird symmetry. CSS style rules are layed on top of the DOM. The CSS property names like "font-weight" are transliterated into

71
"myElement.style.fontWeight". The class of an element can be swapped out. For example: document.getElementById("myText").style.color = "green"; document.getElementById("myText").style.fontSize = "20"; -ordocument.getElementById("myText").className = "regular";
How to Handle Event Handlers? You can add an event handler in the HTML definition of the element like this, <script type="text/javascript"><!-function hitme() { alert("I've been hit!");

}
// --> </script> <input type="button" id="hitme" name="hitme" value="hit me" onclick="hitme()" Or, interestingly enough you can just assign the event's name on the object directly with a reference to the method you want to assign. <input type="button" id="hitme2" name="hitme2" value="hit me2"/> <script type="text/javascript"><!-function hitme2() { alert("I've been hit too!");

}
document.getElementById("hitme2").onclick = hitme2; // --> </script> You can also use an anonymous method like this: document.getElementById("hitme3").onclick = function () { alert("howdy!"); } You can also use the W3C addEvventListener() method, but it does not work in IE yet: <input type="button" id="hitme4" name="hitme4" value="hit me4"/> <script type="text/javascript"><!-function hitme4() { alert("I've been hit four!");

}
if(document.getElementById("hitme4").addEventListener) { document.getElementById("hitme4").addEventListener("click", hitme4, false);

}
// --> </script>
How to remove the event listener: ? <script type="text/javascript"><!-document.getElementById("hitme4").removeEventListener("click", hitme4, false); // --> </script>

72
Key Events "onkeydown", "onkeypress", "onkeyup" events are supported both in ie and standardsbased browsers. <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>
How to make elements invisible ? Change the "visibility" attribute of the style object associated with your element. Remember that a hidden element still takes up space, use "display" to make the space disappear as well.

if ( x == y) { myElement.style.visibility = 'visible'; } else { myElement.style.visibility = 'hidden';

}
How to set the cursor to wait ? In theory, we should cache the current state of the cursor and then put it back to its original state. document.body.style.cursor = 'wait'; //do something interesting and time consuming document.body.style.cursor = 'auto'; How to reload the current page ? window.location.reload(true); how to force a page to go to another page using JavaScript ? <script language="JavaScript" type="text/javascript" ><!-location.href="http://newhost/newpath/newfile.html"; //--></script> How to convert a string to a number using JavaScript? You can use the parseInt() and parseFloat() methods. Notice that extra letters following a valid number are ignored, which is kinda wierd but convenient at times.

73
parseInt("100") ==> 100 parseFloat("98.6") ==> 98.6 parseFloat("98.6 is a common temperature.") ==> 98.6 parseInt("aa") ==> Nan //Not a Number parseInt("aa",16) ==> 170 //you can supply a radix or base
How to convert numbers to strings using JavaScript? You can prepend the number with an empty string var mystring = ""+myinteger; or var mystring = myinteger.toString(); You can specify a base for the conversion, var myinteger = 14; var mystring = myinteger.toString(16);

mystring will be "e".


How to test for bad numbers using JavaScript? the global method, "isNaN()" can tell if a number has gone bad. var temperature = parseFloat(myTemperatureWidget.value); if(!isNaN(temperature)) { alert("Please enter a valid temperature.");

}
What's Math Constants and Functions using JavaScript? The Math object contains useful constants such as Math.PI, Math.E Math also has a zillion helpful functions. Math.abs(value); //absolute value Math.max(value1, value2); //find the largest Math.random() //generate a decimal number between 0 and 1 Math.floor(Math.random()*101) //generate a decimal number between 0 and 100 What's the Date object using JavaScript? Time inside a date object is stored as milliseconds since Jan 1, 1970. new Date(06,01,02) // produces "Fri Feb 02 1906 00:00:00 GMT-0600 (Central Standard Time)" new Date(06,01,02).toLocaleString() // produces "Friday, February 02, 1906 00:00:00" new Date(06,01,02) - new Date(06,01,01) // produces "86400000" What does the delete operator do? The delete operator is used to delete all the variables and objects used in the program ,but it does not delete variables declared with var keyword. How tp create Arrays using JavaScript ? <script type="text/javascript"> var days = new Array(); days[0] = "Sunday" days[1] = "Monday" days[2] = "Tuesday" days[3] = "Wednesday" days[4] = "Thursday"

74
days[5] = "Friday" days[6] = "Saturday" document.write("first day is "+days[0]) </script> This produces first day is Sunday A more compact way of creating an array is the literal notation: <script type="text/javascript"> var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"]; document.write("first day is "+days[0]) </script> This produces first day is Sunday
How to delete an entry using JavaScript? The "delete" operator removes an array element, but oddly does not change the size of the array. <script type="text/javascript"> var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"]; document.write("Number of days:"+days.length); delete days[4]; document.write("<br />Number of days:"+days.length); </script> This produces Number of days:7 Number of days:7 How to use strings as array indexes using JavaScript? Javascript does not have a true hashtable object, but through its wierdness, you can use the array as a hashtable.

<script type="text/javascript"> var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"]; for(var i=0; i < days.length; i++) { days[days[i]] = days[i];

}
document.write("days[\"Monday\"]:"+days["Monday"]); </script> This produces days["Monday"]:Monday
How to use "join()" to create a string from an array using JavaScript? "join" concatenates the array elements with a specified seperator between them.

<script type="text/javascript"> var days = ["Sunday","Monday","Tuesday","Wednesday", "Thursday","Friday","Saturday"]; document.write("days:"+days.join(","));

75
</script> This produces days:Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
How to make a array as a stack using JavaScript? The pop() and push() functions turn a harmless array into a stack

<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
How to shift and unshift using JavaScript? <script type="text/javascript"> var numbers = ["one", "two", "three", "four"]; numbers.unshift("zero"); document.write(" "+numbers.shift()); document.write(" "+numbers.shift()); document.write(" "+numbers.shift()); </script> This produces zero one two shift, unshift, push, and pop may be used on the same array. Queues are easily implemented using combinations. How to create an object using JavaScript? Objects can be created in many ways. One way is to create the object and add the fields directly.

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

76
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]
How to associate functions with objects using JavaScript? Let's now create a custom "toString()" method for our movie object. We can embed the function directly in the object like this.

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

77
</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 What does break and continue statements do? Continue statement continues the current loop (if label not specified) in a new iteration whereas break statement exits the current loop. How to create a function using function constructor? The following example illustrates this It creates a function called square with argument x and returns x multiplied by itself. var square = new Function ("x","return x*x"); What's Prototypes for JavaScript? Objects have "prototypes" from which they may inherit fields and functions. <script type="text/javascript"> function movieToString() { return("title: "+this.title+" director: "+this.director);

}
function movie(title, director) { this.title = title; this.director = director || "unknown"; //if null assign to "unknown" this.toString = movieToString; //assign function to this method pointer

}
movie.prototype.isComedy = false; //add a field to the movie's prototype var officeSpace = new movie("OfficeSpace"); var narnia = new movie("Narni","Andrew Adamson"); document.write(narnia.toString()); document.write(" Narnia a comedy? "+narnia.isComedy); officeSpace.isComedy = true; //override the default just for this object document.write(" Office Space a comedy? "+officeSpace.isComedy); </script>
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";

78
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>

Set 5: What have you used JavaScript for? Typical answers include form validations, user action confirmations, updating an Internet page dynamically and other such answers. I usually ask this question first just to get the candidate talking about JavaScript and see if they have in fact used JavaScript for something.

How do you access an element in an HTML document with JavaScript? Give the element an ID attribute and then use JavaScripts getElementById() function to access that element.

How do you determine how many characters are in a JavaScript string? With the length property of the JavaScript string object.

What datatypes are supported by JavaScript? Number, String, Undefined, null, Boolean. At a minimum, the candidate should identify Number and String.

79

How do you create a date in JavaScript? With the Date object: new Date()

Where does JavaScript date object pull its date from? From the client machine.

What does the isNaN function do? Returns true is the value provided is not a numeric value and false if the number provided is a numeric value.

What is the difference between JavaScript and Java? They are completely different languages.

How do you comment JavaScript code? For single-line comments, begin the line with consecutive forward slashes (//). To comment a block of code, wrap it with /* code */.

What is the JavaScript concatenation operator? The plus sign.

How do you call an external JavaScript file? With the script tag, using the src attribute to reference the path of the JavaScript file.

How do you create a function in JavaScript? Use the function statement.

How do you get the item selected in a dropdown select list? With the selectedIndex property

How do you open a new window?

80

With window.open

How do you remove all options from a dropdown select list? By setting the length property of the dropdown select list to 0.

Demonstrate the syntax for writing a FOR loop. Need an answer similar to: for (i=1;i<=LoopNumber;i++) { //do something } How do you determine the length of an array? With the length property of the array object

How do you load a new URL in a browser? With the location or href property of the window or document object.

What are the different usages of equal signs? One (=) is for assignment. Two (==) is for equality. Three (===) is for strict comparison.

What is ++ used for It is the increment operator. It adds one to a value. What is a transient variable? A transient variable is a variable that may not be serialized.

Which containers use a border Layout as their default layout? The window, Frame and Dialog classes use a border layout as their default layout.

Why do threads block on I/O? Threads block on I/O (that is enters the waiting state) so that other threads may execute while the I/O Operation is performed.

How are Observer and Observable used? Objects that subclass the Observable class maintain a list of observers. When an

81

Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.

Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

What's new with the stop(), suspend() and resume() methods in JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2.

Is null a keyword? The null value is not a keyword.

What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow the component to display normally.

What method is used to specify a container's layout? The setLayout() method is used to specify a container's layout.

Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout.

What state does a thread enter when it terminates its processing?

82

When a thread terminates its processing, it enters the dead state.

What is the Collections API? The Collections API is a set of classes and interfaces that support operations on collections of objects.

Which characters may be used as the second character of an identifier, but not as the first character of an identifier? The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

What is the List interface? The List interface provides support for ordered collections of objects.

How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

What is the Vector class? The Vector class provides the capability to implement a growable array of objects

What modifiers may be used with an inner class that is a member of an outer class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection.

What is the difference between the >> and >>> operators? The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

83

Which method of the Component class is used to set the position and size of a component? setBounds()

How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state.

Which java.util classes and interfaces support event handling? The EventObject class and the EventListener interface support event processing.

Is sizeof a keyword? The sizeof operator is not a keyword.

What are wrapper classes? Wrapper classes are classes that allow primitive types to be accessed as objects.

Does garbage collection guarantee that a program will not run out of memory? Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

What restrictions are placed on the location of a package statement within a source code file?

84

A package statement must appear as the first line in a source code file (excluding blank lines and comments).

Can an object's finalize() method be invoked while it is reachable? An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects.

What is the immediate superclass of the Applet class? Panel

What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

Name three Component subclasses that support painting. The Canvas, Frame, Panel, and Applet classes support painting.

What value does readLine() return when it has reached the end of a file? The readLine() method returns null when it has reached the end of a file.

What is the immediate superclass of the Dialog class? Window.

What is clipping? Clipping is the process of confining paint operations to a limited area or shape. Set 6:

85

what is JavaScript? JavaScript is a scripting language widely used for client-side web development. Explain about run time environment of Javascript? Java script does not have a sophisticated run time of its own but it relies on the web browser of the client. It relies on this run time environment for its functions and methods to perform their duties by which scripts can interact with the user. State some simple usages with Javascript? Some of the simple usages with Javascript are 1) A new pop up window can be made and changed according to the requirements such as no menus, scroll bars, etc. 2) Validation of input values submitted by the user through a web form. 3) Mouse over effects, scroll effects etc which can be changed by the scroll of the mouse pointer over a certain image, etc. Explain about the security functions presents in JavaScript? As JavaScript uses Web as an interface it gives an ample scope for users to transfer malicious scripts. Most of the JavaScript related breaches and wrong doings are due to sandbox or same origin policy. How to read and write a file using JavaScript? I/O operations like reading or writing a file is not possible with client-side JavaScript. However , this can be done by coding a Java applet that reads files for the script. Explain about Cross site scripting? Cross site scripting raises security threats during execution and secured data transfer through web sites. It uses same origin policy. When a malicious script is made to run it discloses private information to the wrong person. This occurs because some one clicks on the request sent by the wrong doer. How do we get JavaScript onto a web page? 1.<script type="text/javascript" > //Define variable /Define function </script> 2.<script language="JavaScript" type="text/javascript"> //Define variable //Define function </script> 3.<script> //Define variable //Define function </script> JavaScript Comment?

86

Single Line Comment- //This is Single Line Comment Multi line Comment - /* This is Multi Line Comment You have learn multi line comment. */ How to open a new window? eg:To open a new window on click of a button. < script type="text/javascript" > function mynewWindow() { window.open( "http://www.google.com/" ); } < /script > < input type="button" onClick=mynewWindow() value="NewWindow" > OR < a href="javascript: window.open(http://www.google.com/)">New Window </a > What is void(0)? void is an operator that is used to return a null value so the browser will not be able to load a new page. which operator is to compare two string? operator == is used to compare two string. eg: var test = "checkeq"; if(test == "checkeq") What are the precautions taken by the web browsers to contain malicious activity with Java Script? Java script activities are restricted by web browsers in two ways they are. 1) First scripts run in sandbox which performs the most basic functions such as executing or running the code or script. This doesn?t allow programming activities. 2) Scripts present in one site cannot have access to other sites; this is done with the help of same origin policy. ^Back to top

How to get CheckBox status whether it is checked or not? Write following code: alert(document.getElementById('checkbox1').checked); if it will be checked you will get true else false. How to get current time in various format (i.e seconds , miliseconds,Day of month etc.) Create a oject of Date class and use its methods. getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM getSeconds() - Number of seconds (0-59)

87

getMinutes() - Number of minutes (0-59) getHours() - Number of hours (0-23) getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday getDate() - Day of the month (0-31) getMonth() - Number of month (0-11) getFullYear() - The four digit year (1970-9999) eg: <script type="text/javascript"> var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() document.write("month is "+ month + "/ " + "day is "+day +" year is "+ "/" + year) or alert(month + "/" + day + "/" + year) </script> How do you submit a form using Javascript? or How do you submit more than one form using Javascript? Use document.forms[0].submit(); (0 refers to the index of the form ? if you have more than one form in a page, then the first one has the index 0, second has index 1 and so on). How do you create a new object in JavaScript? var obj = new Object(); or var obj = {}; What does "1"+2+3 evaluate to? Since 1 is a string, everything is a string, so the result is 123. What does 1+2+"3" evaluate to? Since 1 and 2 are integers, this is number arithmetic, since 3 is a string, it?s concatenation, so 33 is the result. What are undefined and undeclared variables? Undeclared variables are those that are not declared in the program (do not exist at all),trying to read their values gives runtime error.But if undeclared variables are assigned then implicit declaration is done . 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. Are Java and JavaScript the Same? No.java and javascript are two different languages. Java is a powerful object - oriented programming language like C++ whereas Javascript is a client-side scripting language with some limitations.

88

^Back to top

What is the difference between an alert box and a confirmation box? An alert box displays only one button which is the OK button whereas the Confirm box displays two buttons namely OK and cancel.

Das könnte Ihnen auch gefallen