Home / Archive by category 'Javascript'

Javascript

javascript examples

Create and display custom objects using JavaScript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaScript - Create and Display Object Types</title>
</head>
<script language="JavaScript">
 
// ************************************************************************
// CREATE AN AUTOMOBILE USING A CONSTRUCTOR
// ************************************************************************
function Automobile(manufacturer, model, series)
{
 
 
    // ************************************************************************
	// DEFINE AUTOMOBILE ATTRIBUTES
	// ************************************************************************
    this.manufacturer= manufacturer;
    this.model = model;
    this.series = series;
 
}
 
 // ************************************************************************
// DEFINE BEHAVIOR TO RETURN AUTOMOBILES
// ************************************************************************
function getAutomobileInfo()
{
 
 // ************************************************************************
// CREATE VARIOUS AUTOMOBILES OBJECTS
// ************************************************************************
 
	astonMartin1 = new Automobile("Aston Martin", "DB", "DB9 Sports Pack");
	astonMartin2 = new Automobile("Aston Martin", "DB", "DB RS9");
	astonMartin3= new Automobile("Aston Martin", "Vanquish", "V12 S");
	astonMartin4 = new Automobile("Aston Martin", "Vanquish", "Roadster");
 
	bmw1 = new Automobile("BMW","M Series","Coupe");
	bmw2 = new Automobile("BMW","M Series","Convertible");
	bmw3 = new Automobile("BMW","Z Series","Roadster");
	bmw4 = new Automobile("BMW","Z Series","Z3");
 
	jaguar1 = new Automobile("Jaguar","X-Type","Sedan");
	jaguar2 = new Automobile("Jaguar","X-Type","Wagon");
	jaguar3 = new Automobile("Jaguar","XK","Roadster");
	jaguar4 = new Automobile("Jaguar","XK","RS");
 
	mercedesBenz1 = new Automobile("Mercedes Benz","SLR","350");
	mercedesBenz2 = new Automobile("Mercedes Benz","SLR","55");
	mercedesBenz3 = new Automobile("Mercedes Benz","SL-Class","SL600 Roadster");
	mercedesBenz4 = new Automobile("Mercedes Benz","SL-Class","SL65 AMG Roadster");
 
	porsche1 = new Automobile("Porsche","911","Turbo");
	porsche2 = new Automobile("Porsche","911","GT#");
	porsche3 = new Automobile("Porsche","Boxster","2.5");
	porsche4 = new Automobile("Porsche","Boxster","S");
 
// ************************************************************************
// PRINT AUTOMOBILE OBJECTS ONTO WEB PAGE
// ************************************************************************
 
    document.write("Manufacturer:" + astonMartin1.manufacturer + "<br>" +
    			   "Model :" + astonMartin1.model + "<br>" +
    			   "Series :" + astonMartin1.series + "<br><br>");
 
    document.write("Manufacturer:" + astonMartin2.manufacturer + "<br>" +
    			   "Model :" + astonMartin2.model + "<br>" +
    			   "Series :" + astonMartin2.series + "<br><br>");
 
    document.write("Manufacturer:" + astonMartin3.manufacturer + "<br>" +
    			   "Model :" + astonMartin3.model + "<br>" +
    			   "Series :" + astonMartin3.series + "<br><br>");
 
    document.write("Manufacturer:" + astonMartin4.manufacturer + "<br>" +
    			   "Model :" + astonMartin4.model + "<br>" +
    			   "Series :" + astonMartin4.series + "<br><br>");
}
 
 
 
 
</script>
</head>
 
<body bgcolor = "#FFFFFF">
 
<!-- INSERT JAVASCRIPT TO CALL BEHAVIOR-->
<script language="JavaScript">
 
	getAutomobileInfo();
 
</script>
 
</body>
</html>

Create a Monthly Auto Loan Payment Calculator in Javascript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaScript - Loan Calculator</title>
</head>
 
<script language="JavaScript">
			function calculateLoan()
			{
				nMon = document.form1.txtNumerOfMonths.value;
				iRate = document.form1.txtInterestRate.value;
				aFinanced = document.form1.txtAmountFinanced.value;
				mPayment = (iRate * aFinanced)/ nMon;
 
				alert('Your monthly payment would be $ ' + Math.round( mPayment ) );
 
			}
 
	</script>
 
 
</head>
 
<form name="form1">
<body bgcolor="#FFFFFF" LANGUAGE=JavaScript >
 
 
<h2 align="center" class="LabelLarge">Monthly Auto Loan Payment Calculator</h2>
  <table align="center" border="0" cellspacing="8" cellpadding="8">
    <tr>
      <td width="98" align="right" class="boldText"> Number of Months:</td>
      <td width="159">
 
       	<!-- Add a text box to capture Number of Months input-->
      	<input name="txtNumerOfMonths" type="text" size="6" maxlength="6" />
 
      </td>
    </tr>
    <tr>
      <td align="right" class="boldText">Interest Rate:</td>
      <td> <span class="text">
        <input name="txtInterestRate" type="text" size="6" maxlength="6" />
        </span></td>
    </tr>
    <tr>
      <td align="right" class="boldText"> Amount Financed:</td>
      <td>
 
      	<!-- Add a text box to capture Amount Financed input-->
      	<input name="txtAmountFinanced" type="text" size="6" maxlength="6" />
 
      	</td>
    </tr>
    <tr>
      <td colspan="2" valign="top"><div align="center">
 
       <!-- Add a button to execute JavaScript function-->
        <input name="button" type="button" value="Calculate" onClick="calculateLoan()"/>
 
        <input name="reset" type="reset" />
        </div></td>
    </tr>
  </table>
</form>
</body>
</html>

Illustrate how to manipulate JavaScript variables for web pages

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaScript - Creating JavaScript variables for web pages 1</title>
</head>
 
<script language="JavaScript">
 
 // ************************************************************************
// DEFINE BEHAVIOR TO ACCESS ATTRIBUTES
// ************************************************************************
function getFullName()
{
  var firstName, lastName, fullName;
 
  firstName = document.form1.txtFirstName.value;
  lastName  = document.form1.txtLastName.value;
 
  fullName  = firstName + " " + lastName;
 
 // ************************************************************************
// DISPLAY ATTRIBUTE ONTO WEB PAGE
// ************************************************************************
  document.form1.txtFullName.value = fullName;
 
 
}
 
</script>
 
</head>
<body>
 
<h2 font face="Arial" color="#FF0000">
  Credit Application</h2>
 
<font face="Arial" size="3">
<form name="form1">
  <table border="0" cellpadding="0" cellspacing="0">
    <tr>
      <td width="100">First Name:</td>
 
      <!-- Add text box for first name -->
      <td><input type="text" name="txtFirstName" size="14"></td>
 
    </tr>
    <tr>
      <td width="100">Last Name:</td>
 
      <!-- Add text box for last name -->
      <td><input type="text" name="txtLastName" size="14"></td>
 
    </tr>
    <tr>
      <td width="100">Full Name:</td>
 
       <!-- Add text box to display full name -->
      <td><input type="text" name="txtFullName" size="30"></td>
 
    </tr>
    <tr>
      <td width="100"><br><br></td>
      <td>
 
        <!-- Add button to call JavaScript function -->
        <input type="button" value="Show Full Name" onClick="getFullName()">
 
      </td>
    </tr>
  </table>
</form>
</font>
 
</body>
</html>

Example of Encapsulation using JavaScript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>JavaScript - Encapsulation Exercise</title> 
</head> 
 
<body> 
<p> 
  <script language="JavaScript" type="text/JavaScript"> 
 
   // ************************************************************************
   // CREATE AN AUTOMOBILE USING A CONSTRUCTOR
   // ************************************************************************
	function Automobile(speed)
	{
 
   // ************************************************************************
   // PUBLIC PROPERTY -- ANYONE MAY READ/WRITE
   // ************************************************************************
   		this.model = "Standard";
 
   // ************************************************************************
   // PRIVATE VARIABLE AND FUNCTION
   // ONLY PRIVELEGED METHODS MAY VIEW/EDIT/INVOKE
   // ***********************************************************************
		var drivingSpeed = speed;
		var milePerGallonValue1 = 0;
		var milePerGallonValue2 = 0;
 
 
   // ************************************************************************
   // PRIVILEGED METHODS
   // MAY BE INVOKED PUBLICLY AND MAY ACCESS PRIVATE ITEMS
   // MAY NOT BE CHANGED; MAY BE REPLACED WITH PUBLIC FLAVORS
   // ************************************************************************
 
		this.setMilePerGallonEquation = function(param1, param2)
		{
			milePerGallonValue1 = param1;
			milePerGallonValue2 = param2;
		}
 
		this.getMilePerGallonEquation = function()
		{
			return milePerGallonValue1 * milePerGallonValue2;
		}
 
		this.getBaseMilesPerGallon = function()
		{
		   return Math.round(  drivingSpeed / this.getMilePerGallonEquation() );
		}
 
		this.setBaseSpeed = function(newSpeed)
		{
		   drivingSpeed = newSpeed;
		}
 
		this.getBaseSpeed = function()
		{
		   return drivingSpeed;
		}
 
 
	}
 
 
	// ************************************************************************
	// PROTOTYOPE PROERTIES -- ANYONE MAY READ/WRITE (but may be overridden)
	// ************************************************************************
	Automobile.prototype.tankSize = 13;
 
 
	// ************************************************************************
	// STATIC PROPERTIES -- ANYONE MAY READ/WRITE
	// ************************************************************************
	Automobile.opinion = "";
 
 
	// ************************************************************************
	// PUBLIC METHODS -- ANYONE MAY READ/WRITE
	// ************************************************************************
	Automobile.prototype.setIdealSpeed = function(ideal)
	{
		this.idealSpeed = ideal;
	}
 
	Automobile.prototype.getIdealSpeed = function()
	{
		return this.idealSpeed;
	}
 
 
	Mercedes.prototype = new Automobile();
	function Mercedes(autoMobile)
	{
		this.setBaseSpeed( autoMobile.getBaseSpeed() );
	}
 
	Porsche.prototype = new Automobile();
	function Porsche(autoMobile)
	{
		this.setBaseSpeed( autoMobile.getBaseSpeed() );
	}
 
 
	 function performTest()
	 {
		autoMobileObject = new Array(3)
		autoMobileObject[0]  = new Automobile(50);
		autoMobileObject[1] = new Mercedes( autoMobileObject[0] );
		autoMobileObject[2] = new Porsche( autoMobileObject[0] );
 
		autoMobileObject[0].setMilePerGallonEquation(.015, 100);
		autoMobileObject[1].setMilePerGallonEquation(.03, 100);
		autoMobileObject[2].setMilePerGallonEquation(.02, 100);
 
 
		alert("At " + autoMobileObject[0].getBaseSpeed() + " mph. the " + autoMobileObject[0].model +  " version of my Automobile with a " + autoMobileObject[0].tankSize  + " gallon tank will get " + autoMobileObject[0].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ******************************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A BASIC AUTOMOBILE
	// ******************************************************************************************************************
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
 
		alert("At " + autoMobileObject[1].getBaseSpeed() + " mph. the " + autoMobileObject[1].model +  " version of my Mercedes with a " + autoMobileObject[1].tankSize  + " gallon tank will get " + autoMobileObject[1].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ********************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A MERCEDES
	// *********************************************************************************************************
		if( autoMobileObject[1].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
		alert("At " + autoMobileObject[2].getBaseSpeed() + " mph. the " + autoMobileObject[2].model +  " version of my Porsche with a " + autoMobileObject[2].tankSize  + " gallon tank will get " + autoMobileObject[2].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ******************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A PORSCHE
	// ******************************************************************************************************
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
	// ************************************************************************************************************
	// CHANGE THE IDEAL SPEED USING PUBLIC PROPERTIES AND PRIVILEGED METHODS
	// ************************************************************************************************************
		autoMobileObject[0].setIdealSpeed(65);
 
		alert("For best performance the ideal speed is around " +  autoMobileObject[0].getIdealSpeed() + " mph." );
 
		autoMobileObject[0].model = "Luxury";
		autoMobileObject[0].tankSize = 20;
		autoMobileObject[0].setBaseSpeed(70);
 
		alert("However, at " + autoMobileObject[0].getBaseSpeed() + " mph. the " + autoMobileObject[0].model +  " version of my Automobile with a " + autoMobileObject[0].tankSize  + " gallon tank will get " + autoMobileObject[0].getBaseMilesPerGallon() + " miles per gallon." );
 
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
	 }
 
</script> 
 
</p> 
<p align="center"><font size="+3" face="Arial, Helvetica, sans-serif">Encapsulation
  Example</font></p> 
<p align="center">&nbsp;</p> 
<form name="form1" method="post" action=""> 
  <div align="center"> 
 
    <!-- Add button to call JavaScript function --> 
    <input type="button" name="peformTest" value="Perform Test" onclick="javascript:performTest()"> 
 
  </div> 
</form> 
</body> 
</html>

Example to illustrate Polymorphism using JavaScript

To illustrate Polymorphism using JavaScript we define a base object called Automobile with attributes and behaviors. Then we create sub object called Mercedes and Porshce to share the Automobiles attributes and behaviors.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<title>JavaScript - Polymorphism Example</title> 
</head> 
 
<body> 
<p> 
  <script language="JavaScript" type="text/JavaScript"> 
 
	function Automobile(speed)
	{
   // ************************************************************************
   // PUBLIC PROPERTY -- ANYONE MAY READ/WRITE
   // ************************************************************************
   		this.model = "Standard";
 
   // ************************************************************************
   // PRIVATE VARIABLE AND FUNCTION
   // ONLY PRIVELEGED METHODS MAY VIEW/EDIT/INVOKE
   // ***********************************************************************
		var drivingSpeed = speed;
		var milePerGallonValue1 = 0;
		var milePerGallonValue2 = 0;
 
 
   // ************************************************************************
   // PRIVILEGED METHODS
   // MAY BE INVOKED PUBLICLY AND MAY ACCESS PRIVATE ITEMS
   // MAY NOT BE CHANGED; MAY BE REPLACED WITH PUBLIC FLAVORS
   // ************************************************************************
 
		this.setMilePerGallonEquation = function(param1, param2)
		{
			milePerGallonValue1 = param1;
			milePerGallonValue2 = param2;
		}
 
		this.getMilePerGallonEquation = function()
		{
			return milePerGallonValue1 * milePerGallonValue2;
		}
 
		this.getBaseMilesPerGallon = function()
		{
		   return Math.round(  drivingSpeed / this.getMilePerGallonEquation() );
		}
 
		this.setBaseSpeed = function(newSpeed)
		{
		   drivingSpeed = newSpeed;
		}
 
		this.getBaseSpeed = function()
		{
		   return drivingSpeed;
		}
 
 
	}
 
 
	// ************************************************************************
	// PROTOTYOPE PROERTIES -- ANYONE MAY READ/WRITE (but may be overridden)
	// ************************************************************************
	Automobile.prototype.tankSize = 13;
 
 
	// ************************************************************************
	// STATIC PROPERTIES -- ANYONE MAY READ/WRITE
	// ************************************************************************
	Automobile.opinion = "";
 
 
	// ************************************************************************
	// PUBLIC METHODS -- ANYONE MAY READ/WRITE
	// ************************************************************************
	Automobile.prototype.setIdealSpeed = function(ideal)
	{
		this.idealSpeed = ideal;
	}
 
	Automobile.prototype.getIdealSpeed = function()
	{
		return this.idealSpeed;
	}
 
 
	Mercedes.prototype = new Automobile();
	function Mercedes(autoMobile)
	{
		this.setBaseSpeed( autoMobile.getBaseSpeed() );
	}
 
	Porsche.prototype = new Automobile();
	function Porsche(autoMobile)
	{
		this.setBaseSpeed( autoMobile.getBaseSpeed() );
	}
 
 
	 function performTest()
	 {
		autoMobileObject = new Array(3)
		autoMobileObject[0]  = new Automobile(50);
		autoMobileObject[1] = new Mercedes( autoMobileObject[0] );
		autoMobileObject[2] = new Porsche( autoMobileObject[0] );
 
		autoMobileObject[0].setMilePerGallonEquation(.015, 100);
		autoMobileObject[1].setMilePerGallonEquation(.03, 100);
		autoMobileObject[2].setMilePerGallonEquation(.02, 100);
 
 
		alert("At " + autoMobileObject[0].getBaseSpeed() + " mph. the " + autoMobileObject[0].model +  " version of my Automobile with a " + autoMobileObject[0].tankSize  + " gallon tank will get " + autoMobileObject[0].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ******************************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A BASIC AUTOMOBILE
	// ******************************************************************************************************************
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
 
		alert("At " + autoMobileObject[1].getBaseSpeed() + " mph. the " + autoMobileObject[1].model +  " version of my Mercedes with a " + autoMobileObject[1].tankSize  + " gallon tank will get " + autoMobileObject[1].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ********************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A MERCEDES
	// *********************************************************************************************************
		if( autoMobileObject[1].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
		alert("At " + autoMobileObject[2].getBaseSpeed() + " mph. the " + autoMobileObject[2].model +  " version of my Porsche with a " + autoMobileObject[2].tankSize  + " gallon tank will get " + autoMobileObject[2].getBaseMilesPerGallon() + " miles per gallon." );
 
 
	// ******************************************************************************************************
	// CREATE A TEST TO EVALUATE THE BEST MILES PER GALLON FOR A PORSCHE
	// ******************************************************************************************************
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
	// ************************************************************************************************************
	// CHANGE THE IDEAL SPEED USING PUBLIC PROPERTIES AND PRIVILEGED METHODS
	// ************************************************************************************************************
		autoMobileObject[0].setIdealSpeed(65);
 
		alert("For best performance the ideal speed is around " +  autoMobileObject[0].getIdealSpeed() + " mph." );
 
		autoMobileObject[0].model = "Luxury";
		autoMobileObject[0].tankSize = 20;
		autoMobileObject[0].setBaseSpeed(70);
 
		alert("However, at " + autoMobileObject[0].getBaseSpeed() + " mph. the " + autoMobileObject[0].model +  " version of my Automobile with a " + autoMobileObject[0].tankSize  + " gallon tank will get " + autoMobileObject[0].getBaseMilesPerGallon() + " miles per gallon." );
 
		if( autoMobileObject[0].getBaseMilesPerGallon() >= 30 )
		{
			Automobile.opinion = "That's pretty good!";
		}
		else
		{
			Automobile.opinion = "That's not good";
		}
 
		alert( Automobile.opinion );
 
 
	 }
 
</script> 
 
</p> 
<p align="center"><font size="+3" face="Arial, Helvetica, sans-serif">Polymorphism
  Example</font></p> 
<p align="center">&nbsp;</p> 
<form name="form1" method="post" action=""> 
  <div align="center"> 
 
    <!-- Add button to call JavaScript function --> 
    <input type="button" name="peformTest" value="Perform Test" onclick="javascript:performTest()"> 
 
  </div> 
</form> 
</body> 
</html>

Example to illustrate Inheritance using JavaScript

In the example we define a base object called Car, and Create sub object called ferrari that inherits attributes from Car.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>JavaScript - Inheritance Example</title>
</head>
 
<body>
<p>
  <script language="JavaScript" type="text/JavaScript">
 
 
 // ************************************************************************
 //Define a Car object
 // ************************************************************************
 function Car()
 {
	 //Add attributes to the Car
	 this.mileage = 0;
	 this.category = "Vehicle";
 }
 
 
  // ************************************************************************
 // Define a ferrari object
 // ************************************************************************
 function ferrari()
 {
 	 //Add attributes to the ferrari
 	this.mileage = 100;
	this.weight = 400;
 }
 
 // ************************************************************************
 // Use the ferrari prototype to inherit from Car
  // ************************************************************************
 ferrari.prototype = new Car();
 
  //Use the ferrari prototype to inherit from Car
 ferrari.prototype.getMileage = function()
 {
    return this.mileage;
 }
 
 // ************************************************************************
  // Use the ferrari prototype to access Car attributes
  // ************************************************************************
 CashRegister.prototype.getCategory = function()
 {
    return this.category;
 }
 
 // ************************************************************************
 // Define a JavaScript function to drive the test
 // ************************************************************************
 function performTestonInheritance()
 {
 
	  // ************************************************************************
	  // Create an instance of myFerrari
	  // ************************************************************************
	  var myFerrari= new ferrari();
 
	 // ************************************************************************
	 // Access the redifined attribute of ferrari
	 // ************************************************************************
	 alert("The mileage is: " + myFerrari.getMileage() );
 
	 // ************************************************************************
	 // Access the base attribute of ferrari
	 // ************************************************************************
	 alert("The category is: " + myFerrari.getCategory() );
 
 }
 
</script>
 
 
</p>
Inheritance in Javascript  Example
<br/>
<form name="form1" method="post" action="">
  <div align="center">
 
    <!-- Add button to call JavaScript function -->
    <input type="button" name="peformTest" value="Perform Inheritance Test" onclick="javascript:performTestonInheritance()">
 
  </div>
</form>
</body>
</html>

Set background image of excel worksheet using Javascript setbackgroundpicture

var oexcel = new ActiveXObject("excel.application");
oexcel.visible = true;
 
var oworkbook = oexcel.workbooks.add;
var oworksheet = oworkbook.worksheets(1);
oworksheet.setbackgroundpicture("c:\\myimg.jpg");

Example for changing line width of rectangle with Canvas

<!DOCTYPE html>
<html>
	<head>
		<title>Example for changing line width of rectangle with Canvas</title>
		<meta charset="utf-8">
 
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 
		<script>
			$(document).ready(function() {
				var canvas = document.getElementById("myCanvas");
				var ctx = canvas.getContext("2d");
				ctx.lineWidth = 20;
				ctx.strokeStyle = "rgb(255, 0, 0)";//red
				ctx.strokeRect(50, 50, 100, 100);
			});
		</script>
	</head>
 
	<body>
		<canvas id="myCanvas" width="500" height="500">
			<!-- Insert fallback content here -->
		</canvas>
	</body>
</html>

Drawing color filled rectangle with Canvas Example

<!DOCTYPE html>
<html>
	<head>
		<title>Drawing color filled rectangle with Canvas Example</title>
		<meta charset="utf-8">
 
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 
		<script>
			$(document).ready(function() {
				var canvas = document.getElementById("myCanvas");
				var ctx = canvas.getContext("2d");
				ctx.fillStyle = "rgb(255, 0, 0)";  //red
				ctx.fillRect(50, 50, 100, 100);  
			});
		</script>
	</head>
 
	<body>
		<canvas id="myCanvas" width="500" height="500">
			<!-- Insert fallback content here -->
		</canvas>
	</body>
</html>

Drawing filled paths with using Canvas

<!DOCTYPE html>
<html>
	<head>
		<title>Drawing Paths with Canvas Example</title>
		<meta charset="utf-8">
 
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 
		<script>
			$(document).ready(function() {
				var canvas = document.getElementById("myCanvas");
				var ctx = canvas.getContext("2d");
				ctx.beginPath();  
				ctx.moveTo(50, 50);  
				ctx.lineTo(50, 250);  
				ctx.lineTo(250, 250);  
				ctx.closePath();  
				ctx.fill();
			});
		</script>
	</head>
 
	<body>
		<canvas id="myCanvas" width="500" height="500">
			<!-- Insert fallback content here -->
		</canvas>
	</body>
</html>

How to draw a rectangle with outline using Canvas

<!DOCTYPE html>
<html>
	<head>
		<title>Canvas Example</title>
		<meta charset="utf-8">
 
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 
		<script>
			$(document).ready(function() {
				var canvas = document.getElementById("myCanvas");
				var ctx = canvas.getContext("2d");
				ctx.strokeRect(50, 50, 100, 100);
			});
		</script>
	</head>
 
	<body>
		<canvas id="myCanvas" width="500" height="500">
			<!-- Insert fallback content here -->
		</canvas>
	</body>
</html>

Draw a 2D filled rectangle using Canvas

<!DOCTYPE html>
<html>
	<head>
		<title>Canvas from scratch</title>
		<meta charset="utf-8">
 
		<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 
		<script>
			$(document).ready(function() {
				var canvas = document.getElementById("myCanvas");
				var ctx = canvas.getContext("2d");
				ctx.fillRect(50, 50, 100, 100); 
			});
		</script>
 
	</head>
 
	<body>
		<canvas id="myCanvas" width="500" height="500">
		</canvas>
	</body>
</html>

Example of jQuery.getScript() along with callback

The jQuery.getScript() function takes the URL of a file of JavaScript code as its first argument. It asynchronously loads and then executes that code.

// Dynamically load a script from some other server
jQuery. getScript("http://w3mentor.com/js/myscript.js");

// Load a library and use it once it loads

jQuery.getScript("js/myscript.js", function() {
    $('div').myscript();  // Use the library we loaded
});

Load and display a html page every 60 seconds using JQuery Load()

The load() function will asynchronously load the content of, and then insert that content into each of the selected elements, replacing any content that is already there.
// Load and display a html page every 60 seconds

setInterval(function() {
      $("#divid").load("my_report.html");}, 60000);

Detect the browser version in Javascript

<HTML>
<HEAD>
<TITLE>Browser Detecti on</TITLE>
</HEAD>
<body>
<SCRIPT LANGUAGE="JavaScript">
var browsername= navigator.appName
var browserversion = navigator.appVersion
if (browsername == "Microsoft Internet Explorer" )
{ 
document. write(" You are using MS Internet Explorer version " +
browserversion)
}
else
{ 
document. write(" You are using Netscape Navigator version " +
browserversion)
}
</SCRIPT>
</BODY>
</HTML>

Get the properties of the navigator object in Javascript

document.write(navigator.appName)
document.write(navigator.appVersion)
document.write(navigator.platform)
document.write(navigator.cpuClass)

Using Javascript setTimeout() in recursive function

function alertNumbers(num)
{ 
if (num > 10)
return
alert(num)
val = ++num
timerID = setTimeout("alertNumbers(val)", 3000)
}
alertNumbers(0)

Example of using setTimeout() in Javascript

The setTimeout() method evaluates an expression after a specified number of milliseconds have elapsed.

<HTML>
<HEAD>
<TITLE>setTimeout() method</TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function displayAlert()
{ 
alert("5 seconds have elapsed since the button was clicked.")
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
Click the button on the left for a reminder in 5 seconds;
click the button on the right to cancel the reminder before
it is displayed.
<P>
<INPUT TYPE = "button" VALUE = "5-second reminder"
NAME = "remind_button"
onClick = "timerID = setTimeout('displayAlert()',5000)">
</FORM>
</BODY>
</HTML>

Example of using toGMTString() in Javascript

var now = new Date()
var ar1 = now.toGMTString().split(" ")
document.write("The current time in Greenwich is " + ar1[4])

Get the day on which the first day of the month using Javascript

var now = new Date()
now.setDate(1)
ar = new Array(7)
ar[0] = "Sunday"
ar[1] = "Monday"
ar[2] = "Tuesday"
ar[3] = "Wednesday"
ar[4] = "Thursday"
ar[5] = "Friday"
ar[6] = "Saturday"
document.write("The first day of the month occurred on " + ar[now.getDay()])