How to Scroll Top or Bottom of Document Using JavaScript

There are different methods to scroll HTML document using JavaScript, You can scroll the document to Top, Bottom or in any part or to view any element in the document using JavaScript.

To scroll the document using JavaScript, there is a scrollTo() method in window object which takes the X and Y coordinates of a point and sets these as the scrollbar offsets.

The scrollTo() method scrolls the window so that the specified point is in the upper left corner of the view-port. If you specify a point that is too close to the bottom or too close to the right edge of the document, the browser will move it as close as possible to the upper left corner.

How to Scroll Bottom of Document Using JavaScript


You can use the following set of JavaScript codes that scroll the browser to the bottom most page of the document.

var documentHeight=documentElement.offsetHeight;
var viewportHeight=window.innerHeight;
window.scrollTo(0, documentHeight-viewportHeight);

Here the first variable documentHeight specifies the read only offsetHeight properties of any HTML element return its on screen height, in CSS pixels and the returned size include the element border and padding but not margin.

And the second variable, viewportHeight specifies the height of viewport, which is obtained from innerHeight property of window object.

You can execute this code on onclick event of JavaScript hyperlink or on onclik event of any button or text as given below.

function gobottom(){
var documentHeight=document.documentElement.offsetHeight;
var viewportHeight=window.innerHeight;
window.scrollTo(0,documentHeight-viewportHeight);
}

You can call this function gobottom() within HTML file as below.

<input type="button" value="Go To Bottom" onclick="gobottom();"> 

On the other way, you can execute onclick event of button with assigning a function on onload event of window as below.

<script>
window.onload=function(){
var bottom=document.getElementById('bottom');
bottom.onclick=function(){
var documentHeight=document.documentElement.offsetHeight;
var viewportHeight=window.innerHeight;
window.scrollTo(0,documentHeight-viewportHeight);}
</script>

You can call this function by placing id attribute within HTML file as below.

<input type="button" value="Go To Bottom" id="bottom"> 

Preview:




How to Scroll Top of Document Using JavaScript



You can use the following JavaScript code that scroll the browser to the top most page of the document.

window.scroll(0,0);

You can execute this code on onclick event of JavaScript hyper-link or on onclick event of any button or text as given below.

<script>
window.onload=function(){
var top=document.getElementById('top');
top.onclick=function(){window.scrollTo(0,0);}
</script>

You can call this function by placing id attribute within HTML file as given below.

<input type="button" value="Go To Top" id="top"> 

Preview:



How to Scroll Document Automatically Using JavaScript


You can scroll the document automatically using scrollBy() method which is similar to scroll() and scrollTo(), but its arguments are relative and are added to the current scrollbar offsets.

For example, you can use the following code to scroll 10 pixels down every 200ms.

javascript:void setInterval(function(){scrollBy(0,10)}, 200);

How to Scroll Document to View Certain Element Using JavaScript  


Instead of scrolling to a numeric location in document, you can just scroll that a certain element in the document is visible. It can be done easily scrollIntoView() method on the desired HTML element and this method insures that the element on which it is invoked is visible in the viewport.

By default, the scrollIntoView() method tries to put the top edge of the element at or near the top of the viewport. The browser will also scroll the viewport horizontally as needed to make the element visible.



Related Search Terms

Related Posts:

How to Create Table of Contents Using JavaScript


You can create dynamic table of contents for any HTML document using JavaScript which can show the list of headings from h1 to h6 with links to the headings and make easier to navigate through the document.

In this post I am going to describe about the steps to Create Table of Contents Using JavaScript and about the JavaScript codes required to create dynamic table of contents.

To create this set of JavaScript codes for creating table of contents, at first you have to know the different JavaScript concepts like selecting elements, document traversal, setting element attributes, setting innerHTML property, creating nodes and inserting then into the document.


Steps to Create Table of Contents Using JavaScript


At first create window.onload function that runs automatically when the document finishes loading as given below.

window.onload=function(){

function getSelectedText(){
if (window.getSelection)
return window.getSelection().toString()+"
"+document.URL;
else if (document.selection)
return document.selection.createRange().text+"
"+document.URL;
}
var toc=document.getElementById("TOC");
if(!toc) {
toc=document.createElement("div");
toc.id="TOC";
document.body.insertBefore(toc, document.body.firstChild);
}

When the above function runs, it first looks for a document element with an id of "TOC". If there is no such element it creates on at the start of the document.

Add the following codes to the function to find all <h1> through <h6> tags and sets them as headings.

var headings;
if (document.querySelectorAll)
headings=document.querySelectorAll("h1, h2, h3, h4, h5, h6");
else
headings=findHeadings(document.body, []);

Then recursively traverse the document body looking for headings using function: findHeadings(root, sects){  }

Initialize an array: var sectionNumber=[0,0,0,0,0,0]; that keeps track of section numbers and add section numbers to each section numbers to each section heading and wrap the headings in named anchors so that the TOC can link to them.

Write CSS code to style created table of contents. Where all entries have a class "TOCEntry" and the section headings from <h1> to <h6> have class name "TOCLevel1" to "TOCLevel6" and the section number inserted into headings have class "TOCSectNum".

Full CSS Code To Style Table of Contents


 Here is a full CSS code within <style> </style> tag to style table of contents.

<style>
#TOC {border:solid black 1px; margin:10px; padding:10px;}
.TOCEntry{font-family:sans-serief;}
.TOCEntry a{text-decoration:none;}
.TOCLevel1{font-size:17pt; font-weight:bold;}
.TOCLevel2{font-size:16pt; font-weight:bold;}
.TOCLevel3{font-size:15pt; font-weight:bold;}
.TOCLevel4{font-size:14pt; margin-left:.25in;}
.TOCSectNum{display:none;}
</style>

Full JavaScript Code To Create Table of Contents



Here is a full JavaScript Code To Create Table of Contents within <script> </script> tag.

<script>
window.onload=function(){

function getSelectedText(){
if (window.getSelection)
return window.getSelection().toString()+"<br/>"+document.URL;
else if (document.selection)
return document.selection.createRange().text+"<br/>"+document.URL;
}

var toc=document.getElementById("TOC");
if(!toc) {
toc=document.createElement("div");
toc.id="TOC";
document.body.insertBefore(toc, document.body.firstChild);
}
var headings;
if (document.querySelectorAll)
headings=document.querySelectorAll("h1, h2, h3, h4, h5, h6");
else
headings=findHeadings(document.body, []);

function findHeadings(root, sects){
for(var c=root.firstChild; c!=null; c=c.nextSibling){
if (c.nodeType!==1) continue;
if (c.tagName.length==2 && c.tagName.charAt(0)=="H")
sects.push(c);
else
findHeadings(c, sects);
}
return sects;
}

var sectionNumbers=[0,0,0,0,0,0];

for(var h=0; h<headings.length; h++) {
var heading=headings[h];

if(heading.parentNode==toc) continue;

var level=parseInt(heading.tagName.charAt(1));
if (isNaN(level)||level<1||level>6) continue;

sectionNumbers[level-1]++;
for(var i=level; i<6; i++) sectionNumbers[i]=0;

var sectionNumber=sectionNumbers.slice(0, level).join(".");

var span=document.createElement("span");
span.className="TOCSectNum";
span.innerHTML=sectionNumber;
heading.insertBefore(span, heading.firstChild);
heading.id="TOC"+sectionNumber;
var anchor=document.createElement("a");
heading.parentNode.insertBefore(anchor, heading);
anchor.appendChild(heading);

var link=document.createElement("a");
link.href="#TOC"+sectionNumber;
link.innerHTML=heading.innerHTML;

var entry=document.createElement("div");
entry.className="TOCEntry TOCLevel" + level;
entry.appendChild(link);

toc.appendChild(entry);
}
};

</script>

You can see the preview of Table of contents generated by JavaScript code above. If you have any problem or difficulties while implementing the above JavaScript code, you are welcomed to mention on the comment session at the bottom this post.



Related Search Terms

Related Posts:

How to Select Document Elements Using JavaScript?

You have to select the document elements for manipulation of elements of document to complete any task for the document design or action of the document using JavaScript codes.

There are number of ways to select elements to query a document for an element or elements in order to manipulate elements of the document, to obtain or select the element objects that refer to those document elements.

The different ways to select elements to query a document are explained below.

Selecting Elements By ID Attribute


Any of the HTML element can have the unique id attribute within the document. You can select an element based on this unique id with getElementById() method of the document object.

To select any element with id 'elt' you can use the following code.

var elt=document.getElementById('elt');

Selecting Elements By Name Attribute


Name attribute assigns the name of the element and it does not have to be unique. You can select the elements by name using getElementsByName() method.

To select any element with name 'address' you can use the following code.

var addresses=document.getElementsByName("address");

If there is a only one element with a given name, you use the name directly as the document property to assign the value of the element as given below.

To get the element for the from <form name="addresses">, you can use the following code.

var addresses=document.addresses;

Selecting Elements By TagName


You can select any HTML or XML elements by tagName using the getElementsByTagName() method of the document object. To select all <p> elements, you can use the following code.

var para=document.getElementsByTagName("p");

You can select any element with given tagName with specifying the position number according to the order of the document. You can select first <p> element of the document using the following.

var firstpara=document.getElementsByTagName("p")[0];

Also to find all <span> elements inside the first <p> element of document, you can write.

var firstpara=document.getElementsByTagName("p")[0];
var firstparaspans=firstpara.getElementsByTagName("span");

Selecting Elements By CSS Class


It is the another way to select elements from the document. You can select one or more elements with the given class name by using getElementsByClassName() method.

To select elements with ClassName 'color' you can use the following code.

var colors=document.getElementByClassName("color");

If you have to select elements having more than one class name, can do as below.

To select any element with ClassName 'color'  and 'design' you can use the following code.

var colors=document.getElementByClassName("color design");

Selecting Elements By CSS Selectors


You can also select document elements with specifying CSS selectors which are used on CSS style-sheet. You can select one or more elements with the given CSS selectors by using querySelectorAll method.

To select an element with id 'nav' you can use the following code.

var nav=document.querySelectorAll("#nav");

To select a paragraph written in english you can use the following code.

var eng=document.querySelectorAll("p[lang="en"]");

Here are other examples of CSS selectors to select elements from the document.

#log span     // selects any <span> descendant of the element with id="log"

#log>span     // Selects <span> child of the element with id="log"

*[name="x"]     // Selects any element with a name="x" attribute.


You can also use document.all[] method, which is a collection that represented all the elements in the document as the following although this method is replaced by standard methods like getElementById() and getElementsByTagName().

document.all[0]         // Selects the first element in the document
document.all["navbar"]         // Selects all elements with id or name="navbar"
document.all.tags("div")     // Selects all <div> elements in the document
document.all.tags("p")[0]     // The first <p> in the document



Related Search Terms

Related Posts:

How to Show Pop Up Window Using JavaScript

You can show pop up window By using JavaScript window.open() method which loads specified URL into a new or existing window and returns the window object that represents that window.

The window.open() method takes four optional arguments which are URL of the window, Window name, attributes of window, the boolean value to replace or not the current window.

Syntax: window.open("windowname.html", "New Window", "width=width in pixel, height=height in pixel, status=yes or no, resizable=yes or no");

The first argument of window.open() method allows to display given URL in the new window. If the argument is omitted, the special blank-page URL:about:blank is used.

The second argument of window.open() method is a string which specifies a window name. If the argument is omitted, the special name "_blank" is used which opens a new, unnamed window.

The third optional argument of window.open() method is a comma-separated list of size and features attributes for the new window to be opened. If you omit this argument, the new window is given a default size and has a full set of UI components: a menu bar, status bar, toolbar etc.

The fourth optional argument of window.open() is useful only when the second argument names an existing window. It is a boolean value that indicates whether the URL specified as the first argument should replace the current entry in the window's browsing history: written true, or create a new entry in the window's browsing history: written false. And omitting the argument is same as written false.

Here is an example to open a small but resizable browser window with a status bar but no menu bar, tool-bar, or location bar.

window.open("new_window.html", "New Window", "width=400, 
height=350, status=yes, resizable=yes");

Here status bar is showing using status=yes and the window is resizable  using resizable=yes, if you don't want to show status bar, you can use status=no and want the fixed window, can use resizable=no in the argument.

To open a new pop up window on onclick event of button, you can use the following code.

<input type=button name="open" value="Open window"
onclick="window.open('http://www.siteforinfotech.com/p/about-us.html
','new window', 'width=400, height=350, status=yes, resizable=yes');">

Preview:



To open a new pop up window on <a> href link, you can use the following code.

<a href="javascript:void window.open
('http://www.siteforinfotech.com/p/about-us.html', 'new window',
'width=400, height=350, status=yes, resizable=yes');
">Open Pop Up window</a>

Preview:

Open Pop Up window

The return value of the window.open() method is the window object that represents the named or newly created window. You can use this window object in you JavaScript code to refer to the new window and to specify the properties on it as given below.

var w=window.open();
w.alert("You are going to visit:http://www.siteforinfotech.com");
w.location="http://www.siteforinfotech.com";


Here you can specify other properties like width, height, status, resizable given above. And you can assign variable w for any windows event or on any event trigger using JavaScript.

"Pop Up" and "Pop Under" advertisements are made by using this method window.open() while you browse the web. JavaScript codes that tries to open a pop up window when the browser first loads, browsers blocked them. So the advertisements are made to run pop up windows only in response to a user action such as clicking on button and clicking on link. 




Related Search Terms


Related Posts:

How to go Back Browsing History Using JavaScript

The history property of the window object refers to the history object for the window. Using history in JavaScript you can go back to the previous browsing history. 

The history object models the browsing history of a window as a list of document and document states and the length property of the history object specifies the number of elements in the browsing history list.

The history object has back() and forward() methods that behave like the browser's back and forward buttons do, they make the browser go backward or forward one step in its browsing history.

history.back();     // Go back to the browsing history
history.forward(); //Go forward to the browsing history

Creating Buttons for History Back and Forward


You can create buttons to navigate browsing history back and forward using the following code.

<input type=button name="back" value="Go Back" onclick="history.back();">

<input type=button name="forward"
value="Go Forward"onclick="history.forward();">

Preview:




A third method, go(), takes an integer argument and can skip any number of pages forward or backward in the history list.

history.go(-2) //go back 2, like clicking the back button twice

Creating Buttons for History Back and Forward for Specific Page


You can create buttons to navigate browsing history two step back using the following code.

<input type=button name="backward2"
value="Go Back 2" onclick="history.go(-2);">

Preview:




Using history.go() method, if you want to go forward, can use positive arguments and if you want to go back, can use negative argument and the number used on the argument represents how many steps to go back or forward.

For example, if you want to go two step forward to the browsing history, can use history.go(2); and if you want to go three step backward to the browsing history, can use history.go(-3);
 
If  a window contains child windows such as <iframe> elements, the browsing histories of the child windows are chronologically interleaved with the history of the main window.  This means that calling history.back(); on the main window may cause one of the child windows to navigate back to a previously displayed document but leave the main window in its current state.

If a frame is contained within another frame that is contained within a top-level window, that frame can refer to the top-level window as parent. For parent window to navigate back to a previously displayed document you can use parent property as below.

parent.history.back();


I have described here some methods of navigating browsing history back and forward using JavaScript . If you know other more methods of navigating browsing history back and forward using JavaScript, you are welcomed to mention on the comment session at the bottom this post.



Related Search Terms


Related Posts:

How to Click Button Using JavaScript?

Buttons on a web-page allows users to submit data or to do any action on it and generally the actions are performed by clicking on it. Different types of buttons are used on web-page and they may be inside a form or outside a form for certain action to be performed. Buttons used within a form may be Submit Button, Reset Button, Browse Button etc.

You can set the actions performed by submit and reset buttons on a form with in a &lt;form&gt; tag as below.

<form action="submitpage.html" onsubmit="return validate(this)"
onreset="return conform()" method="post">
<!--Other Form Elements-->
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>

In the above code, when submit button was clicked it goes to the page "submitpage.html" after validating the form by the function validate() and when reset button was clicked it clears all the form data after displaying conformation box by the function conform().

It is easier to do any task on clicking event of a button by executing certain JavaScript functions when the button was clicked. There are different ways to execute JavaScript codes on button click. In this post I am going to describe about those different methods of clicking buttons using JavaScript.

Different Ways to Click Button Using JavaScript


You can click button using JavaScript with the different methods given below.

With directly specifying JavaScript Built-in function on onClick event of Button


<input type="button" value="Display Time" 
onClick="alert(new Date().toLocaleTimeString());">


Preview:


With creating a JavaScript function and specifying it on onClick event of Button as given on the previous post: "How to create Timer Using JavaScript?"


<script>

var c=0

var t

function timedCount()

{

document.getElementById('txt').value=c

c=c+1

t=setTimeout("timedCount()", 1000)

}

</script>

<input type="button" value="Start Count" onClick="timedCount()">

<input type="button" value="0" id="txt">

Preview:
 

With creating a JavaScript function along with specifying onClick event of Button


<script>

window.onload=function(){

var btn=document.getElementById('btn');

btn.onclick=function(){alert("You Have Clicked Button");}

};

</script>

<input type=button id='btn' value='click me'>

Preview:
 

With specifying single function for multiple buttons having same class name by using for loop on onClick event of button


<script>

window.onload=function(){

var btns=document.getElementsByClassName('bt');

for(var i=0; i<btns.length; i++){

var bt=btns[i];

bt.onclick=function(){alert("You Have Clicked Button");}

}

};

</script>

<input type=button class='bt' value='Button 1'>

<input type=button class='bt' value='Button 2'>

<input type=button class='bt' value='Button 3'>

Preview:
 

I have described here some methods of clicking buttons using JavaScript . If you know other more methods of clicking buttons using JavaScript, you are welcomed to mention on the comment session at the bottom this post.



Related Search Terms


Related Posts:

How to Create JavaScript Bookmarklet?

Bookmarklet is a small JavaScript code which is saved on a browser's bookmark while bookmarking JavaScript: URL. It is a mini program that can be easily launched from the browser's menus or toolbar.

The code in a bookmarklet runs as if it ware a script on a page and can query and set document content presentation, and behavior. As long as a bookmarklet does not return a value, it can operate on whatever document is currently displayed without replacing that document with new content.

 How to Create JavaScript Bookmarklet?


To create bookmarklet on your browser, either you can create HTML file containing JavaScript: URL and can bookmark it right clicking on the link and selecting something like bookmark link or dragging the link to your bookmarks toolbar or you can directly add new bookmark with add new bookmark option on the browser.

Here is a simple HTML code to create JavaScript URL link with a simple JavaScript code to display current time which I have previously mentioned on my previous post "How to Write JavaScript Function as URL in Hyperlink".

<a href="javascript:alert(new Date().toLocaleTimeString());"> 
check the document without writing the docment</a>

To check bookmarklet for your browser, save on bookmark the link given below which is generated from the code given above.

Check the document without writing the document

Another example of JavaScript:URL link in an <a> tag is given below, which opens a simple JavaScript expression evaluator that allows you to evaluate expressions and execute statements in the context of the page.

<a href='javascript:
var e="", r=""; /*expression evaluate the result*/
do{
/*display expression and result and ask for a new expression*/
e=prompt("Expression:"+e+"\n"+r+"\n", e);
try{r="Result:"+eval(e);} /*try to evaluate the expression*/
catch(ex){r=ex;}
} while(e); /*continue until no expression entered or cancel clicked*/
void 0;'>
Javascript Evaluator </a>

Even the above JavaScript:URL is written in multiple lines, the HTML parser treats it a single line, and in a single line code comments using // will not work so comments are created using /* and */. The preview of the code above is given below.

  JavaScript Evaluator

You can save this link on your browsers bookmarks and check it by lunching the bookmark.




Related Search Terms


Related Posts:

How to Write JavaScript Function as URL in Hyperlink?

You can write JavaScript function as like URL in hyperlink on href attribute of <a>....</a> tag. Writing JavaScript codes in a URL is another way that JavaScript code can be included in the client side using javascript: protocol specifier. This special protocol type specifies that the body of the URL is an arbitrary string of JavaScript code to be run by the JavaScript interpreter.

The "resource" identified by a javascript: URL is the return value of the executed code, converted to a string. If the code has an undefined return value, the resource has no content.

You can use a javascript: URL anywhere you'd use a regular URL: on the href attribute of <a> tag, on the action attribute of a <form>, on the click event of a button, on the method like window.open() etc.

The syntax for writing JavaScript function within href attribute of <a> tag is given below.

<a href="javascript:myfunction();">JavaScript Link</a>

And the syntax for writing JavaScript function within the action attribute of a <form> tag is given below.

<form action="myfunction();" onsubmit="return validate(this);" method="post"> .......</form>

An example for getting new date using javascript function as a hyperlink is given below.

<a href="javascript:new Date().toLocaleTimeString();"> What time is it?</a>

While using such functions on a hyperlink, some browsers like Firefox and IE execute the code in the URL and use the returned string as the content of a new document to display.

Just as when following a link to an http:URL, the browser erases the current document and displays the new one. The value returned by the code above does not contain any HTML tags.

Other browsers like chrome and safari do not allow URLs like the one above to overwrite the containing document, they just ignore the return value of the code. But they support the JavaScript code to display the returned content on alert box as below.

<a href="javascript:alert(new Date().toLocaleTimeString());"> check the document without writing the docment</a>

In the above cases, the javascript:URL serves the same purpose as an on-click event handler. The link The link above would be better expressed as an on-click handler on a <button> element. The <a> element generally reserved for hyperlinks that load new documents.

If you want to open a new document using a javascript: URL which does not overwrite the document, you can use void operator with window.open method as given below.

<a href="javascript:void window.open('http://www.siteforinfotech.com/p/javascript-programming-tutorials.html');">Open link on new window</a>


If you want to open a new document using a javascript: URL which overwrite the current document, you can use location.replace method as given below.

<a href="javascript:location.replace('http://www.siteforinfotech.com/p/javascript-programming-tutorials.html');">Open window using location.replace</a>


Like HTML event handler attributes, JavaScript URLs are a holdover from the early days of the web and generally avoided in modern HTML. JavaScript: URLs are very useful if you need to test a small snippet of JavaScript code, you can type a javascript:URL directly into the location bar of your browser. And another most powerful use of Javascript:URLs is in browser bookmarks.

Related Search Terms


Related Posts:


How to create Timer Using JavaScript?

With JavaScript it is possible to execute some code not immediately after a function is called,  but after a specified time interval. This is called timing events. With timing events you can create timer like stopwatch, clock, quiz timer and many more.

For timing events in JavaScript, there are four methods that are used are

setTimeout(): This method of the window object schedules a function to run after a specified number of milliseconds elapses. setTimeout() returns a value that can be passed to clearTimeout() to cancel the execution of the scheduled function.

syntax: var t=setTimeout("javascript statement", milliseconds)

setInterval(): setInterval is like setTimeout() except that the specified function is invoked repeatedly at intervals of the specified number of milliseconds.

syntax: var t=setInterval("javascript statement", milliseconds)

clearTimeout() and clearInterval(): Like setTimeout() and setInterval() returns a value that can be passed to clearTimeout() or clearInterval() to cancel any future invocation of the scheduled function.

syntax: clearTimeout(setTimeout_variable)
syntax: clearInterval(setInterval_variable)

Execution of Function with Timer


Here is a function which will be executed after 5 seconds on button click. Here the first parameter of setTimeout() is a string that contains a

JavaScript statement and the second parameter indicates how many milliseconds from now you want to execute the first parameter.

<script>
function timedMsg()
{
var t=setTimeout("alert('5 seconds!')", 5000)
}
</script>

<form>
<input type="button" value="Dispaly timed alertbox!" onClick="timedMsg()">
</form>

Preview of Timer



How to Create Stopwatch using JavaScript Timer


With using JavaScript timing event, you can create a stopwatch which counts the time when clicked on start button and stops counting when clicked on stop button.

Here is a JavaScript and HTML code for creating stopwatch.

<script>
var c=0
var t
function timedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()", 1000)
}
function stopCount()
{
clearTimeout(t)
}
function clearTimer()
{
document.getElementById('txt').value=0
c=0
}
</script>

<form>
<input type="button" value="Start Count" onClick="timedCount()">
<input type="button" value="0" id="txt">
<input type="button" value="Stop Count" onClick="stopCount()">
<input type="button" value="Clear Timer" onClick="clearTimer()">
</form>

Preview of Stopwatch




How to Create Timer for Online Quiz


With using JavaScript timing event, you can create timer for online quiz, which count down from the given time and finishes quiz after given time finished. 

Here is a JavaScript and HTML code for creating timer for online quiz.

<script>
var s=59
var m=5
var q
function quizCount()
{
document.getElementById('timer').value=m+":"+s+" remaining"
s=s-1
q=setTimeout("quizCount()", 1000)
if (s<1)
{ m=m-1; s=59;}

if (m<0)
{
quizStop();
}
}
function quizStop()
{
clearTimeout(q)
document.getElementById('timer').value="Your Time Was Finished"
}
</script>

<form>
<input type="button" value="Start Count" onClick="quizCount()">
<input type="button" value="Quiz Timer" id="timer">
<input type="button" value="Stop Count" onClick="quizStop()">
</form>

Here the timer was set for 5 minutes, it countdowns from 5 to 0 and when time finishes it gives alert for time finished. You can add function to calculate and display quiz results on quizStop().

Preview of Online Quiz Timer





Related Search Terms


Related Posts:


How to create a Simple calculator Using HTML and JavaScript

Here are the steps to create a simple calculator using HTML and JavaScript which can evaluate simple arithmetic on integer numbers. Two types of inputs text and button are used here on a table within a form element and OnClick event was used to insert button values on the screen or to evaluate the numbers.

Steps to create a Simple calculator Using HTML and JavaScript


1. At first Insert a <form> element within <body> tag.
2. Create a table using <table> .....</table> tag.
3. Insert two types of Input text and button within table data of table row using <tr><td>....</td></tr> tag.
4. Assign OnClick event for all the buttons having numbers and arithmetic operators.
5. Give blank value for Clear(C) button.
6. Use eval() function to evaluate the numbers on OnClick event of equal to sign button.

Full HTML code for a Simple HTML calculator


<html>
<head></head>
<body>
<h3>Simple Calculator</h3>
<br/>
<form Name="calc">
<table border=2>
<tr>
<td colspan=4><input type=text Name="display"></td>
</tr>
<tr>
<td><input type=button value="0" OnClick="calc.display.value+='0'"></td>
<td><input type=button value="1" OnClick="calc.display.value+='1'"></td>
<td><input type=button value="2" OnClick="calc.display.value+='2'"></td>
<td><input type=button value="+" OnClick="calc.display.value+='+'"></td>
</tr>
<tr>
<td><input type=button value="3" OnClick="calc.display.value+='3'"></td>
<td><input type=button value="4" OnClick="calc.display.value+='4'"></td>
<td><input type=button value="5" OnClick="calc.display.value+='5'"></td>
<td><input type=button value="-" OnClick="calc.display.value+='-'"></td>
</tr>
<tr>
<td><input type=button value="6" OnClick="calc.display.value+='6'"></td>
<td><input type=button value="7" OnClick="calc.display.value+='7'"></td>
<td><input type=button value="8" OnClick="calc.display.value+='8'"></td>
<td><input type=button value="x" OnClick="calc.display.value+='*'"></td>
</tr>
<tr>
<td><input type=button value="9" OnClick="calc.display.value+='9'"></td>
<td><input type=button value="C" OnClick="calc.display.value=''"></td>
<td><input type=button value="=" OnClick="calc.display.value=eval(calc.display.value)"></td>
<td><input type=button value="/" OnClick="calc.display.value+='/'"></td>
</tr>
</table>
</form>
</body>
</html>



Preview of Simple HTML calculator



Related Search Terms


Related Posts:


How to use Round, Random, Min and Max in JavaSript

Round, Random, Min and Max are the methods used in math object in JavaSript. Math object allows you to perform common mathematical tasks. The math object includes several mathematical values and functions. Yo do not need to define the math object before using it. In this post I am describing How to use Round, Random, Min and Max in JavaSript.

How to use Round() in JavaScript


Using round() method in math object, you can round the given numbers as given below.

<script>
document.write(Math.round(0.60) +"<br/>");
document.write(Math.round(0.40) +"<br/>");
document.write(Math.round(0.49) +"<br/>");
document.write(Math.round(-3.69) +"<br/>");
document.write(Math.round(-6.10) +"<br/>");
</script>

Preview:


How to use Random() in JavaScript


You can use the random() method in math object,you can return a random number between 0 and 1 as given below.

<script>
document.write(Math.random());
</script>

Preview:


How to use Max() in JavaScript


Using max() method in math object, you can return the number with the highest value of two specified numbers as the following.

<script>
document.write(Math.max(9,3) +"<br/>");
document.write(Math.max(-5,7) +"<br/>");
document.write(Math.max(10,21) +"<br/>");
document.write(Math.max(-5,-9) +"<br/>");
document.write(Math.max(6.12,7.98) +"<br/>");
</script>

Preview:



How to use Min() in JavaScript


Using min() method in math object, you can return the number with the highest value of two specified numbers as the following.

<script>
document.write(Math.min(9,3) +"<br/>");
document.write(Math.min(-5,7) +"<br/>");
document.write(Math.min(10,21) +"<br/>");
document.write(Math.min(-5,-9) +"<br/>");
document.write(Math.min(6.12,7.98) +"<br/>");
</script>

Preview:


There are also other more methods on JavaScript math object to perform common mathematical tasks which are listed below along with their description. You can use them as the methods given above.
  • abs(x):  Returns the absolute value of a number
  • ceil(x): Returns the value of a number rounded upwards to the nearest integer
  • exp(x):  Returns the value or E^x.
  • floor(x): Returns the value of a number rounded downwards to the nearest integer.
  • log(x):  Returns the natural logarithm (base E) of a number.
  • pow(x,y): Returns the value of x to the power of y.
  • sqrt(x):  Returns the square root of a number.



Related Search Terms

How to Concatenate, Join and Sort Array in JavaScript?

In the previous post, I have already described about "How to Loop Through JavaScript Array". Along with accessing an element of an array using looping statements, you can also concatenate, join and sort an array in JavaScript. In this post you will learn about How to Concatenate, Join and Sort Array in JavaScript.

How to Join Two Arrays using Concat()


Using concat() method, you can join to arrays array1 and array2 as below.

<script>
var array1=new Array(3);
array1[0]="Saab"
array1[1]="Volvo"
array1[2]="BMW"

var array2=new Array(3);
array2[0]="Yamaha"
array2[1]="Honda"
array2[2]="Bajaj"

var array3=array1.concat(array2);

for(i=0; i<array3.length;i++)
{
document.write(array3[i]+"<br/>")
}
</script>

Preview:



Here the method array1.concat(array2) concentrates two arrays array1 and array2.

How to Put Array Elements Into a String using Join()


You can use the join() method to put all the elements of an array into a string as the following script.


<script>
var array1=new Array(3);
array1[0]="Yamaha"
array1[1]="Honda"
array1[2]="Bajaj"

document.write(array1.join()+"<br/>");
document.write (array1.join("."));
</script>


Preview:



How to Sort String Array using sort()


Using sort() method, you can sort the elements of string array as given below.

<script>
var array1=new Array(6);
array1[0]="Saab"
array1[1]="Volvo"
array1[2]="BMW"
array1[3]="Yamaha"
array1[4]="Honda"
array1[5]="Bajaj"

document.write(array1+"<br/>");
document.write (array1.sort());
</script>

Preview:


How to Sort Numeric Array using sort()


Using sort() method, you can sort the elements of numeric array as given below.

<script>
var array2=new Array(6);
array2[0]=10
array2[1]=5
array2[2]=40
array2[3]=25
array2[4]=35
array2[5]=95
function sortNumber(a,b) {return a - b;}

document.write(array2+"<br/>");
document.write (array2.sort(sortNumber));

</script>

Preview:



There are also other more methods for manipulating array elements, which are listed below along with their description. You can use them as the methods given above.

  • pop(): Removes and returns the last element of an array
  • push(): Adds one or more elements to the end of an array and returns the new length.
  • reverse(): Reverses the order of the elements in an array
  • toString(): Converts an array to string and returns the result.

Read Next:How to use Round, Random, Min and Max in JavaSript

Related Search Terms

فيديو الأسبوع