Java

Javascript Interview Questions and Answers part 2



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.

What’s a way to append a value to an array? 
arr[arr.length] = value;

What is this keyword? 
It refers to the current object.

 

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

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>

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

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 “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”;
-or-
document.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>

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

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



/* */