Objective Questions on CSS Syntax and Property set-6



1) ....... media type is used for use with printed material and documents viewed onscreen in print preview mode.

A. Print

B. Projection

C. Aural

D. Screen



2) In CSS length measurement unit ....... defines a measurement in picas.

A. pi

B. pc

C. pt

D. px



3) In CSS length measurement unit ......defines a measurement in screen pixel.

A. pi

B. pc

C. pt

D. px




4) ........ defines a measurement relative to a font's x-height. The x-height is determined by the height of the font's lowercase letter x.

A. cm

B. em

C. ex

D. hx




5) Which of the following is the correct CSS code to set the background color of all h1, h2 and h3 elements to orange.

A. h1.h2.h3{background-color:orange;}

B. h1, h2, h3{background-color:orange;}

C. h1 h2 h3{background-color:orange;}

D. h1, h2, h3{set-background:orange;}




6) The CSS selector E>F selects ...

A. direct decedents

B. adjacent siblings

C. preceding siblings

D. all elements



7) The CSS selector E-F selects .....

A. direct decedents

B. adjacent siblings

C. preceding siblings

D. all elements



8) ........... selects all elements of E that have an attribute attr that starts with the value given in a list of hyphen-separated values.

A. E[attr-=value]

B. E[attr|=value]

C. E[attr~=value]

D. E[attr^=value]



9) .......... selects all elements of E that have the attribute attr that begins with the given value.

A. E[attr-=value]

B. E[attr|=value]

C. E[attr~=value]

D. E[attr^=value]



10) A single @charset rule can be used in a/an ........... to define character set encoding of the style rules and values.

A. external sheet

B. internal sheet

C. inline codes

D. Both A and B



11) An ......... rule can be used to define style rules for multiple media types in a single embedded style sheet.

A. @embedded

B. @media

C. @page

D. @multiple



12) An ........... rule is used to define a page block for printed styles. Generally, within this construct we see various CSS properties like size, page, and margin to control the dimensions of the page.

A. @embedded

B. @media

C. @page

D. @print



13) Which of the following are the sub properties of background property used in CSS Except.

A. background-color

B. background-scroll

C. background-image

D. background-repeat



14) Which of the following is the default value of background-image property in CSS.

A. url

B. inherit

C. none

D. both A and B



15) State whether the following statements are True or False.

i) Background-position property determines how a background image is positioned within the canvas space by associated element.

ii) The default value for background-attachment property is fixed.

iii) The background image requires a URL(complete or relative) to link it to the source image specified with the url() syntax.

A. i-True, ii-True, iii-False

B. i-True, ii-False, iii-False

C. i-False, ii-True, iii-True

D. i-True, ii-False, iii-True



16) Which of the following is/are the sub properties of border property in CSS.

A. border-width

B. border-style

C. border-color

D. All of the above



17) Match the following CSS cursor resizing property with their descriptions.

i) e-resize a) pointing north south.

ii) ne-resize b) pointing northwest-southeast

iii) nw-resize c) pointing northeast-southwest

iv) n-resize d) pointing east-west(left-right)

A. i-d, ii-c, iii-b, iv-a

B. i-c, ii-b, iii-a, iv-d

C. i-b, ii-c, iii-d, iv-a

D. i-d, ii-a, iii-b, iv-c



18) ......... property controls how spaces, tabs, and newline charters are handled in an element.

A. visibility

B. white-space

C. tab-space

D. line-space



19) ......... property controls the algorithm used to lay out the table, cells, rows, and columns.

A. table-layout

B. cell-layout

C. row-column-layout

D. None of the above



20) ......... property is used to force or prohibit a printing page break within an element.

A. page-break-outside

B. page-break-inside

C. printing-page-break

D. page-break-element


Read More »

Solved Multiple Choice Questions on Basic CSS set-5



1) All of the following statement about CSS styles are True Except.

A. External style sheets can set and update styles for many documents at once.

B. In inline style, it can be easily control style to a single character instance.

C. In some cases @import is used in inline styles

D. There is no additional network requests required to retrieve style information.



2) ............. requires extra download round-trip for t he style sheet, which might delay page rendering, particularly when multiple files are in use.

A. External Style Sheets

B. Document Wide Style

C. Inline Style

D. All of the above



3) For .............., it needs to reapply style information throughout the document and outside documents.

A. External Style Sheets

B. Document Wide Style

C. Inline Style

D. All of the above



4) Which of the following is the correct example of document wide style in CSS.

A. <h1 style="color:red;"> I am red !</h1>

B. <h1 color="red"> I am red ! </h1>

C. <style type="text/css" media="all"> h1{color:red;}</style>

D. <style type="stylesheet" media="all"> h1{color:red;}</style>



5) .......... overrides any document styles in the absence of !import directive.

A. Document Wide Style

B. Inline Style

C. External Style Sheets

D. All of the above



6) Which of the following statements are True about the types of CSS stylesheets.

i) Document wide style can easily control style document by document.

ii) Document wide style needs additional network requests to retrieve style information.

iii) With external style sheets, style information is cached by the browser, so there's no need to repeat.

A. i-True, ii-True, iii-False

B. i-True, ii-False, iii-True

C. i-True, ii-False, iii-False

D. i-False, ii-True, iii-True



7) Media type defined under CSS 2.1 for use with low resolution teletypes, terminals, or other devices with limited display capabilities is

A. tt

B. tv

C. ttd

D. tty



8) Which of the following is/are the media types defined in CSS.

A. aural

B. embossed

C. print

D. All of the above



9) As defined in CSS2 ........ selects all elements of E that have a space separated list of values for attr where one of those values is equal to the given value.

A. E[attr~=value]

B. E[attr|=value]

C. E[attr=value]

D. All of the above



10) Which of the following selector selects all elements of E that have the attribute attr that ends with the given value in CSS3.

A. E[attr#=value]

B. E[attr$=value]

C. E[attr^=value]

D. E[attr!=value]



11) Which of the following CSS code sets the font style to italic on all p tags that have one word in their title equal to test.

A. p[title~="Test"]{font-style:italic;}

B. p[title|="Test"]{font-style:italic;}

C. p[title="Test"]{font-style:italic;}

D. p[title^="Test"]{font-style:italic;}



12) Which of the following CSS code sets the font-weight to bold on all a tags that have their href attribute set to http://www.siteforinfotech.com

A. a[href*="http://www.siteforinfotech.com"]{font-weight:bold;}

B. a[href~="http://www.siteforinfotech.com"]{font-weight:bold;}

C. a[href$="http://www.siteforinfotech.com"]{font-weight:bold;}

D. a[href="http://www.siteforinfotech.com"]{font-weight:bold;}



13) Match the following CSS selectors with their respective definitions.

i) a:link a) specifies the link as it is being pressed.

ii) a:active b) specifies the link after being pressed

iii) a:visited c) specifies the unvisited link

A. i-a, ii-c, iii-b

B. i-b, ii-a, iii-c

C. i-c, ii-a, iii-b

D. i-a, ii-c, iii-b



14) The following CSS code strong:first-of-type{font-size: bigger;}

A. sets the font size bigger on the first strong tag of its parent.

B. sets the font size bigger on all of the strong tag of its parent.

C. sets the font size bigger on the strong tag if only the child of its parent.

D. None of the above options.



15) Which of the following selector is not defined in CSS3.

A. :root

B. :empty

C. :not(a)

D. :lang(value)



16) Which of the following is/are the sub properties of borders property in CSS.

i) border

ii) border-top

iii) border-top-style

iv) border-bottom-position

v) border-top-width

A. i, ii, iv and v

B. ii, iii, iv and v

C. i, ii, iii and v

D. iii, iv and v



17) Which of the following is not the CSS propery to display the generated content.

A. conter-reset

B. counter-stop

C. counter-increment

D. content



18) The CSS properties page-break-before, page-break-after, page, and size are included in which CSS property.

A. print property

B. print preview property

C. page setup property

D. All of the above



19) Which of the following is/are the sub properties of background property in CSS.

A. background-color

B. background-image

C. background-attachment

D. All of the above



20) In CSS3, ......... selects an element that has no children.

A. :not(a)

B. :empty

C. :root

D. :lang(value)


Answers:


1) C. In some cases @import is used in inline styles
2) A. External Style Sheets
3) C. Inline Style
4) C. <style type="text/css" media="all"> h1{color:red;}</style>
5) B. Inline Style
6) B. i-True, ii-False, iii-True
7) D. tty
8) D. All of the above
9) A. E[attr~=value]
10) B. E[attr$=value]
11) A. p[title~="Test"]{font-style:italic;}
12) D. a[href="http://www.siteforinfotech.com"]{font-weight:bold;}
13) C. i-c, ii-a, iii-b
14) A. sets the font size bigger on the first strong tag of its parent.
15) D. :lang(value)
16) C. i, ii, iii and v
17) B. counter-stop
18) A. print property
19) D. All of the above
20) B. :empty


Related Posts:

For more Multiple Choice Questions (MCQs): Click Here

Read More »

How to Create Show/Hide Effect in Image SlideShow Using JQuery


The fadeOut() effect presented on the post "How to create Fade Effect in Image Slideshow using JQuery" which I have already posted, makes elements invisible but retains space for them in the document layout.

The hide() method, by contrast, removes the elements from the layouts as if the CSS display property was set to none. When invoked with no arguments, hide() and show() simply hide or show the selected elements immediately. With a duration argument, however, they animate the hiding or showing process. hide() shrinks an element's width and height to 0 at the same time that it reduces the element's opacity to 0. show() reverses the process.

toggle() changes the visibility state of the elements, it is invoked on, if they are hidden, it calls show(), and it they are visible, it calls hide(). As with show() and hide(), you must pass a toggle() to get an animated effect. Passing true to toggle() is the same as calling show() with no arguments. Note also that if you pass two or more function arguments to toggle() it registers event handlers.

Here is an example that invokes methods for show/hide effect animation. The first image has show() effect animation, second image has hide() effect animation and the third animation has toggle() effect animation.

$("#img1").show(2000);
$("#img2").hide(3000);
$("#img3").toggle(1000);

Here are some examples to show show(), hide() and toggle() effects using jQuery.

Example of show() Effect 


<script>
  $(document).ready(function(){
    $(#btn1).click(function () {
      $("#img1").show(2000);
    });
  });
  </script>

<input type=button id="btn1" value="Start Show"/>
<img id="img1" src="img1.jpg"> 



Example of hide() Effect


<script>
  $(document).ready(function(){
    $(#btn2).click(function () {
      $("#img2").hide(3000);
    });
  });
  </script>

<input type=button id="btn2" value="Start Hide"/>
<img id="img2" src="img2.jpg"> 



Example of toggle() Effect 


<script>
  $(document).ready(function(){
    $(#btn3).click(function () {
      $("#img3").toggle(1000);
    });
  });
  </script>
<input type=button id="btn3" value="Start Toggle"/> <img id="img3" src="img3.jpg">


Full jQuery code for Show/Hide effect image animation


<script 

src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</script>

<style>
.show_hide
{
 box-shadow:1px 1px 5px 2px #6DC83C;
 position:relative;
 width:448px;
 height: 336px;
 border-radius:19px;
}

.show_hide img
{
 border-radius:19px;
 position:absolute;
 left:0;
 top:0;
}

</style>

<script>
$(function(){
 $('.show_hide img:gt(0)').hide();
 setInterval(function(){$('.show_hide :first-child').hide(3000).next('img').show(3000).end

().appendTo('.show_hide');}, 6000);
});
</script>

<div class="show_hide">
<img src="img1.JPG" />
 <img src="img2.JPG" />
 <img src="img3.JPG" />
</div>

Read More »

How to Create Animated Visual Effects Using jQuery


You can create animated visual effects by setting the CSS visibility property, i.e. making elements appearing and disappearing. Along with making an element appear and disappear, we might reduce the value of its opacity property over the certain period. This king of animated visual effect creates a more pleasing experience for user and jQuery makes them easy.

jQuery defines simple methods such as fadeIn() and fadeOut() for basic visual effects. You can also use an animate() method for producing more complex custom animations. 

Every animation has a duration that specifies how long the effect should last for. You can specify this as a number of milliseconds or by using a string. The string "fast" means 200ms and the sting "slow" means 600ms. If you specify a duration string that jQuery does not recognize, you will get a default duration of 400ms. 

$("#animation").fadeIn(); 
// It fades an element in over 400ms
$("#animation").fadeOut("fast"); 
// It fade outs over 200ms
$("#animation").fadeIn(5000);
//It fades an element in over 5000ms

You can also define new duration names by adding new string-to-number mappings to jQuery.fx.speeds as given below. 

jQuery.fx.speeds["medium-fast"]=3000;
jQuery.fx.speeds["medium-slow"]=5000;

Here is an example to create animated visual effects using methods fadeIn() and fadeOut() in jQuery 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
jQuery.fx.speeds["medium-slow"]=3000;
jQuery.fx.speeds["very-slow"]=5000;
$(document).ready(function(){
 $("#btn1").click(function(){
$("#animation1").fadeIn(); 
$("#animation3").fadeIn(5000);
$("#animation5").fadeIn("medium-slow");
});
 $("#btn2").click(function(){
$("#animation2").fadeOut("fast");
$("#animation4").fadeOut("very-slow");
});
 });
</script>
<input type=button id="btn1" value="Start FadeIn"/><br/>
<div id="animation1" style="display:none;background:pink;">It fades an element in over 400ms</div><br/>
<div id="animation3" style="display:none;background:red">It fades an element in over 5000ms</div><br/>
<div id="animation5" style="display:none;background:yellow">It fades an element in over 3000ms</div><br/>

<input type=button id="btn2" value="Start FadeOut"/><br/>
<div id="animation2" style="background:red">It fade outs over 200ms</div><br/>
<div id="animation4" style="background:pink">It fade outs over 5000ms</div><br/>

Preview:







It fade outs over 200ms

It fade outs over 5000ms

You can also set the value of the document that was animated using a function as argument. Here is a jQuery code which quickly fade in an element and when it is visible, display some text in it. 

<script>
$(document).ready(function(){
$("#btn4").click(function(){
$("#message").fadeIn("fast", function() {$("#message").text("Hello this is animation");});
});});
</script>
<input type=button id="btn4" value="Start Animation"/><br/>
<div id="message" style="color:red"></div>

Preview:




Read More »

How to Alter HTML Document Structure using jQuery?


HTML documents are represented as a tree of nodes rather than a linear sequence of characters, insertions, deletions, and replacements are not as simple as they are for strings and arrays. In jQuery there are some methods for making more complex changes to a document.

There are number of method in jQuery for inserting and replacing elements, copying elements, wrapping elements and deleting elements. For insertion and replacement of elements in HTML document, you can use the methods append(), prepend() and replacewith(). 

You can copy HTML elements using clone() method and wrapp the elements using wrap(), wrapInner() and wrapAll() methods. For deletion of the element you can use empty(), reomve() and unwrap() methods. 

How to Insert and Replace Elements using jQuery 


You can use different methods to insert and replace elements using jQuery, each of the methods takes an argument that specifies the content that is to be inserted into the document. 

The inserting can be made into or before or after or in place of each selected elements. If the content to be inserted is an element that already exists in the document, it is moved from current location.
The append() method inserts an element at the end of selected element, prepend() method inserts an element at start of selected element and replaceWith() method replaces one selected element with another. For append(), prepend() and replacewith() the second argument is the current content of the element as an HTML string. 

There are before() and after() methods, which can be used to insert before and after of each selected elements. For before() and after() the function is invoked with no second argument. 

Here are some examples of jQuery codes for inserting and replacing elements using jQuery. 

$("#clr").append("<br/>"+message); 
// It adds a content at end of the #clr element

$("h1").prepend(":"); 
// It adds colon sign at the star of each <h1>

$("h1").before("<hr/>");
// It insert horizontal line before each <h1> element

$("h1").after("<hr/>");
// It insert horizontal line after each <h1> element

$("hr").replaceWidth("<br/>");
// It replaces <hr/> elements with <br/>

$("h2").each(function(){
var h2=$(this);
h2.replaceWith("<h1>"+h2.html()+"</h1>");
});
// It replaces <h2> with <h1> keeping the content.

Similary, you can use appendTo(), prependTo(), insertAfter(), insertBefore and replaceAll() methods for the same purpose as given in the example below. 

$("<br/>"+message).appendTo("#clr"); 
// It adds a content at end of the #clr element
$(document.createTextNode(":")).prependTo("h1"); 
// It adds colon sign at the star of each <h1>
$("<hr/>").insertBefore("h1");
// It insert horizontal line before each <h1> element
$("<hr/>").insertAfter("h1");
// It insert horizontal line after each <h1> element
$("<br/>").replaceAll("hr");
// It replaces <hr/> elements with <br/>
 

How to Copy Elements using jQuery 


If you insert elements that are already part of the document, those elements will simply be moved, not copied to their new location. 

If you want to copy elements to a new location instead of moving them, you must first make a copy with the clone() method. clone() makes and returns a copy of each selected element and all the descendent's of those elements. 

An example for copying elements using clone() method is given below. 

$(document.body).append("<div id="linklist"><h1>List of Links</h1></div>");
//It appends a new div with id "linklist", to the end of the document
$("a").clone().appendTo("#linklist");
//It copy all links in the document and insert them into that new div
$("#linklist>a").after("<br/>");
//It insert <br/> elements after each link so they display on separate lines

Read More »

How to Get and Set Element Attributes using jQuery


Some of the simplest and most common, operations on jQuery objects are those that get or set the value of HTML attributes, CSS styles, element content, or element geometry. In this post I am going to describe the methods to get or set HTML element attributes using jQuery.

How to Get and Set HTML Attributes using jQuery


You can get or set HTML attributes using attr() method in jQuery. The attr() method handles browser incompatibilities and special cases and allows you to use either HTML attributes names or their JavaScript property equivalents.

Here are some examples of uses of attr() method for getting or setting HTML attributes.

$("form").attr("action");  
// It gets the action attribute from the first form.

$("#icon").attr("src", "icon.gif");  
// It sets the src attributes for image with id icon.

$("a").attr("target", "_blank");  
// It set the target attributes for all links to load in new windows 

$("a").attr("target", function(){
 if(this.host==location.host) return "_self"
 else return "_blank";
});

This function sets the attribute of all external links load in new windows and internal links load in the same window.

There is another method related to attr() is removeAttr(), which is related function that completely removes an attributes from all selected elements.

Here an example of uses of removeAttr() method for removing HTML attributes.

$("a").removeAttr("target");

It removes the target attribute of link and makes all links load in the same window.

How to Get and Set CSS Attributes using jQuery


The css() method is very much like attr() method, but is works with the CSS styles of an element rather than the HTML attributes of the element.

When querying style values, css() returns the current style of the element and the returned value may come from the style attribute or from a style-sheet.

Here are some examples getting and setting CSS attributes using attr() method.

$("h1").css("font-weight"); 
// It gets font weight of first <h1>

$("h1").css("font-variant", "smallcaps"); 
// It sets font-variant property of <h1> to smallcaps.

$("h1").css({backgroundColor:"black",textColor:"white",
 fontVariant:"small-caps", padding: "10px 2px 4px 20px", 
 border:"dotted black 4px"});   
// It sets multiple styles at once for <h1>

How to Get and Set CSS Classes using jQuery


jQuery defines convenience methods for working with the class attribute. addClass() and removeClass() add and remove classes from the selected elements. toogleClass() adds classes to elements that don't already have them and removes classes from those that do. hasClass() tests for the presence of a specified class.

Here are are some examples for adding css classes, removing css classes, toggling css classes and testing css classes.

Adding CSS Classes

$("h1").addClass("hilite");  
// It adds a class to all <h1> elements

$("h1+p").addClass("hilite first"); 
// It adds two classes to elements after <h1>

$("section").addClass(function(n){return "scetion"+n;}); 
// It passes a function to add a custom class to each matched element

Removing CSS classes

$("p").removeClass("hilite");  
// It removes a class from all p elements

$("p").removeClass("hilite first"); 
// It removes two classes from <p> elements

$("section").removeClass(function(n){return "scetion"+n;}); 
// It passes a function to remove a custom class to each matched element

Toggling CSS Classes

$("tr:odd").toggleClass("oddrow"); 
// It adds the class if it is not there or remove if it is.

$("h1").toggleClass("big bold");   
// It toggles two classes at once. 

$("h1").toggleClass(function(n){
return "big bold h1-" +n; });  
// It toggles a computed class or classes.

$("h1").toggleClass("hilite", true); 
// It works like addclass

$("h1").toggleClass("hilite", false); 
// It works like removeclass

Testing CSS Classes

$("p").hasClass("first")  
// It tests any p element have class first

$("#lead").is("first") 
// It test any element with id lead have class first

The hasClass() method is less flexible than addclass(), removeClass, and toggleClass(). hasClass() works for only a single class name and does not support function arguments. It returns true if any of the selected elements has the specified CSS class and returns false if none of them do. The is() method is more flexible and can be used for the same purpose.

How to Get and Set HTML Form Values Using jQuery


For setting and querying the value attribute of HTML form elements val() method is used and it is also used for querying and setting the selection state of check-boxes, radio buttons, and select elements. Here are some examples of getting and setting HTML form values using val() method. 

$("#firstname").val()  
// It gets value from the firstname text field.

$("select #extras").val() 
// It gets array of values from <select multiple< from element. 

$("input:radio[name=ship]:checked").val() 
// It gets value of checked radio button.

How to Get and Set Element Content Using jQuery


The text() and html() methods query and set the plain-text or HTML content of an element or elements. When invoked with no arguments, text() returns the plain text content of all descendant text nodes of all matched elements. This works even in browsers that do not support the textContent or innerText properties. Here are some examples of getting and setting element content using text() and html() method 

var title=$("head title").text() //It gets document title
var headline=$("h1").html() 
//It gets the html of first <h1> element

$("h1").text(function(n,current){
 return "$" + (n+1) + ": "+current }); 
// It gives section number for each headings

How to Get and Set Element Geometry Using jQuery


To query or set the position of an element, use the offset() method. This method measures positions relative to the document and returns them in the form of an object with left and top properties that hold the X and Y coordinates. It you pass an object with these properties to the method, it sets the position you specify. Here are some examples of getting and setting element geometry using offset() method 

var elt=$("#sprite");
var position=elt.offset(); 
// It gets the current position of an elememt
position.top +=100;
// It changes its Y coordinate 100px.
elt.offset(position);

Read More »

How to Use jQuery With HTML?


jQuery() is a single global function defined by jQuery library. This function is so frequently used that the library also defines the global symbol $ as a shortcut for it.

This single global function with two names is the central query function for jQuery. For example, if you need to ask for the set of all <div> elements in a document, write the following code.

var divs=$("div");

The value returned by the jQuery() function represents a set of zero or more DOM elements is known as a jQuery object. jQuery objects define many methods for operating on the sets of elements they represent.

How to Obtain jQuery


jQuery library is free software. You can download if from http://www.jquery.com. Once you have download the code, you can include it in your web pages with a <script> element as given below.
<script src="jquery-1.11.2.min.js"></script>

Here the "min" in the filename indicates that this is the minimized version of the library, with unnecessary comments and whitespace removed, and internal identifiers replaced with shorter ones.

And another way to use jQuery in your web application is to allow a Content Distribution Network (CDN) to serve it using a URL like one of these. 

Google CDN


https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js
https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js

Microsoft CDN


http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.3.min.js
http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.2.min.js

jQuery CDN


http://code.jquery.com/jquery-2.1.3.min.js
http://code.jquery.com/jquery-1.11.2.min.js


If you use Google CDN, you can use "1.11" to get the latest release in the 1.11.x series, or just "1" to get the most current release less than 2.0.

The major advantage of loading jQuery from well-known URLs like these is that, because of jQuery's popularity, visitors to your website will likely already have a copy of the library in the browser's cache and no download will be necessary.

Read More »

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


Read More »

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


Read More »

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

Read More »

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. 

Read More »

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.

Read More »

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.

Read More »

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.


Read More »

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.

Read More »

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



Read More »

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>


Read More »

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.

Read More »

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 More »
next