Moving Image Inside HTML page: Javascript ( A Small Fun Application )

Write a xHTML program to take input from the user and move the image to the corresponding location(position), using Javascript.

Note: ( CSS – Cascading StyleSheet )
Static Positioning does not have top and left properties, so an image which is positioned as Static can’t be moved.
Absolute positioning: The image moves to the new location according to the values of top and left.
Relative positioning: Here the image moves relative to its original position. From its original position, it applies the new top and left value and moves accordingly.

Video Explaining The Code:



YouTube Link: http://www.youtube.com/watch?v=cJtMtd2QmMM [Watch the Video In Full Screen.]



Write a xhtml program, and use the form input tags and accept two values from the user. Using document.getElementById, get those user entered values and assign it to two variables.
Similarly, using the div tags id, change the style information and assign the user entered values to div tags top and left position whenever user hits the “move” button.

Source Code: (move.html)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 
<html>
 <head><title> Move Image </title>
 
 <style type="text/css">
  	#kids { position: relative; top: 200px; left: 400px; }
 </style>
 
 <script type="text/javascript">
 
  function moveIt()
 {
	var x = document.getElementById("x").value;
	var y = document.getElementById("y").value;
 
	var kids = document.getElementById("kids").style;
 
	kids.top = x + "px";
	kids.left = y  + "px";
 
 }
 
 </script>
 </head>
 <body>
 
	<form>
		X axis: <input type="text" id="x"><br />
		Y axis: <input type="text" id="y"><br />
		<input type="button" value=" Move " onclick="moveIt()" >
	</form>
 
<div id="kids">
  <img 
  src="http://technotip.org/wp-content/themes/NewsDen/images/logo.gif" 
  width="220" height="42">
</div>
 
 </body>
</html>

Fun Application Code:
We have made some minor changes to the above code to get the x and y co-ordinates from the cursor position automatically.

Here, we do not accept input directly from the user. We have removed the html form using html comments(

<!--  Comments -->

) and invoke the javascript function moveIt when the user moves his mouse on the html document.
When there is onmousemove event, most browsers automatically throw some objects and we accept it in our function(as parameter) and make use of it. Some browsers like Microsoft’s Internet Explorer do not throw the event object automatically, so we assign it manually using the below code

   if( !evnt )
		evnt = window.event;

Explanation of above two lines of code:
If evnt does not exist, then assign the event to evnt variable.

Also Make Sure To Watch This Video: Event Object: Javascript

Now using the clientX and clientY or screenX and screenY property of the event object, we track the x and y co-ordinates of the cursor and assign that value to the top and left position of the image(div tag which wraps the image tag).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
 
<html>
 <head><title> Move Image </title>
 
 <style type="text/css">
  	#kids { position: relative; top: 200px; left: 400px; }
	#x, #y { font-size: 24pt; color: red; }
 </style>
 
 <script type="text/javascript">
 
	document.onmousemove = moveIt;
 
  function moveIt(evnt)
 {
	if( !evnt )
		evnt = window.event;
 
	var x = evnt.clientX;
	var y = evnt.clientY;
 
	var kids = document.getElementById("kids").style;
 
	kids.top = x + "px";
	kids.left = y  + "px";
 
	document.getElementById("x").innerHTML = x;
	document.getElementById("y").innerHTML = y;
 
 
 }
 
 </script>
 </head>
 <body>
X:<span id="x"></span><br />
Y:<span id="y"></span>
<!--
	<form>
		X axis: <input type="text" id="x"><br />
		Y axis: <input type="text" id="y"><br />
		<input type="button" value=" Move " onclick="moveIt()" >
	</form>
-->
<div id="kids">
 <img 
 src="http://technotip.org/wp-content/themes/NewsDen/images/logo.gif" 
 width="220" height="42">
</div>
 
 </body>
</html>

Hence, whenever the user move his mouse pointer over the html document the image starts moving according to the new value generated for the each move.

Advertisements

Event Object: Javascript

“Browser throws object automatically whenever an event occurs.” This is true with most browsers, except Microsoft’s Internet Explorer.
To solve the browser incompatibility and to make our programs work the same way in all major browsers(including Internet Explorer – IE ), we need to write the coding with little smartness!

What does this program do?
Here we will track the users cursor movement and display the X and Y axis of the cursor position in the browser window.
We will make use of onmousemove event and clientX and clientX properties.

We will also show how to catch the event objects and make proper use of them and how to handle a situation when the event object is not passed automatically.



YouTube Link: http://www.youtube.com/watch?v=UPqPooGsAHs [Watch the Video In Full Screen.]



HTML Code:
Here we have taken a form with two empty input tags. Latter with the help of javascript program we will fill the value of these empty input html tags.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
<html>
 <head>
  <title> Events In Javascript </title>
  <script type="text/javascript" src="event.js"></script>
 </head>
 <body>
 
  <form>
	X axis: <input type="text" id="x"><br />
	Y axis: <input type="text" id="y">
 
  </form>
 
 </body>
</html>

To link our html and the javascript files, we need to write this code in the head tag of html file:

   <script type="text/javascript" src="event.js"></script>

Javascript code:

1
2
3
4
5
6
7
8
9
10
11
12
 
	document.onmousemove = call;
 
	function call(evnt) {
 
		if( !evnt )
			evnt = window.event;
 
		document.getElementById("x").value = evnt.clientX;
		document.getElementById("y").value = evnt.clientY;
 
	}

Here, when we move our mouse over the html document, call() function is invoked.
If the event object is not automatically passed by the browser i.e., if the browser is internet explorer, then we manually assign the event to evnt object using below code:

 
		if( !evnt )
			evnt = window.event;

With clientX and clientY property of the event object, we will assign the x axis and y axis value to the empty input tags using its id.

Text Stacking: CSS & JavaScript

Develop and demonstrate, using Javascript, a xHTML document that contains three short paragraphs of text, stacked on top of each other, with only enough of each showing so that the mouse cursor can be placed over some part of them. When the cursor is placed over the exposed part of any paragraph, it should rise to the top to become completely visible.

Video Explaining the program:



YouTube Link: http://www.youtube.com/watch?v=vTkIcqEaOs8 [Watch the Video In Full Screen.]


HTML coding:

Info:
Div tag is a block-level element.

In HTML code we have used unique ids for the div tags: one, two, three. The same ids have been used in CSS(to assign style information) as well as in the Javascript(for functionality) file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
 
<html>
 <head>
  <title>Text Stacked On Top Of EachOther: CSS & JavaScript</title>
  <link rel="stylesheet" href="style.css" type="text/css">
  <script type="text/javascript" src="stacked.js"></script>
 </head>
 <body>
 
	<div id="one" onmouseover="moveIt('one')">
		Microsoft Dominates!<br />
		Windows 7 is getting popular!
	</div>
 
	<div id="two" onmouseover="moveIt('two')">
		Apple may Dominate!<br />
		iTV may takeoff in the market!
	</div>
 
	<div id="three" onmouseover="moveIt('three')">
		Google Rocks!!<br />
		We all know that!!!! :-) 
	</div>
 
 </body>
</html>

Cascading StyleSheet(CSS) coding:
In CSS, we assign Verdana as the font for the entire body, with font size as 24 points(pt).
Next, using the id(present in the HTML code below) we assign styling information to each div tags.
Positioning is absolute.
We have varied 20 pixels from top and 20 pixels from left for each div, so that the text overlaps on each other leaving 20 pixels(from top as well as from left) of space for mouse over.
We have also changed the background-color and foreground-color of the text inside div tags, so that each div stands out from the other.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 
body {
	font-family: verdana;
	font-size: 24pt;
}
 
#one {
	position: absolute;
	top: 200px;
	left: 300px;
 
	background-color: black;
	color: white;
}
 
#two {
	position: absolute;
	top: 220px;
	left: 320px;
 
	background-color: cyan;
	color: black;
}
 
#three {
	position: absolute;
	top: 240px;
	left: 340px;
 
	background-color: pink;
	color: yellow;
}

JavaScript coding:
In Javascript, we declare a variable called topLayer and assign it the value three(which is a id name).
Next inside the function moveIt we declare another variable called oldTop, in which we store the style information of topLayer variable(which contains id “three”).
Similarly, in variable newTop we store the style information of the toTop(which we receive as parameter to moveIt function).

We can also combine those two lines of code as shown below:

1
2
3
 
    var oldTop   =   document.getElementById(topLayer).style.zIndex = "0";
    var newTop =   document.getElementById(toTop).style.zIndex = "10";

Note: Higher the value of z-index(in CSS) or zIndex(in javascript), nearer it looks to the user viewing it.

In javascript, while writing style property name, make use of capital latter immediately after the hyphen and eleminate the actual hyphen.

Example:
In CSS: background-color
In JS : backgroundColor

In CSS: z-index
In JS : zIndex

In CSS: font-weight
In JS : fontWeight

In CSS: border-style
In JS : borderStyle

etc, etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
var topLayer = "three";
 
function moveIt(toTop) {
 
    var oldTop   =   document.getElementById(topLayer).style;
    var newTop =   document.getElementById(toTop).style;
 
    oldTop.zIndex   = "0";
    newTop.zIndex = "10";
 
    topLayer = document.getElementById(toTop).id;
 
 
}

At the end of the function we reset the value of topLayer variable with the id name which invoked the function.
Note:
Make sure to save all these (.html, .css and .js : HTML, CSS and Javascript) files in the same folder or else change the path in the header as appropriate.

Find Position of Left most Vowel: JavaScript

Develop and demonstrate a xhtml file which uses javascript program to find the first occurrence or the left most vowel in the user entered string.
Input: A String.
Output: Position of the left most or first occurrence of the vowel in the user entered string.

Video Explaining The JavaScript Code:

YouTube Link: http://www.youtube.com/watch?v=ni3diSb5Y40 [Watch the Video In Full Screen.]


Work Flow:
Step 1: Prompt the user to enter a string, store the user entered string in a variable called str.

Step 2: Convert the string in str to upper case using toUpperCase function. Now the original value of str is lost and its equivalent upper case string has been stored.
Ex: str = str.toUpperCase();

Step 3: Now find the length of the entered string using length function. i.e., variableName.length; Ex: str.length;

Step 4: Using for loop, loop through the string from 0 to the string length(which is calculated in Step 3).

Step 5: Using chatAt function fetch one character at a time from str and store it in variable chr. Ex: chr = str.charAt(i);

Step 6: Now compare the value in chr with upper case vowels: A, E, I, O, U.

Step 7: If chr matches any vowel then break out of for loop.

Step 8: If the value of i after coming out of the for loop, is less than string length then print the value of i which is the position of the left most occurrence of the vowel. If the value of i is greater than or equal to string length, then Vowel not found in the entered string.

Javascrip coding explained in above video:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 
<html>
 <head><title>Finding Left most Vowel in the Input String</title></head>
 <body>
	<script type="text/javascript">
	<!--
		var chr = "";
		var str = prompt("Enter the string","");
 
		str = str.toUpperCase();
 
		for(var i = 0; i < str.length; i++)
		{
			chr = str.charAt(i);
 
			if(chr == 'A' || chr == 'E' || chr == 'I' 
                                             || chr == 'O' || chr == 'U')
				break;
		}
 
		if( i < str.length )
			document.write("The position of the
                                           left most vowel is "+(i+1)+"<br />");
		else
			document.write("No vowel found in the entered string");
 
	// -->
	</script>
 
 </body>
</html>

Input/Output:
If Microsoft is the input string, then the position of the first occurrence of vowel is 2. i.e., i.
For Oracle, O is a vowel, so the position is 1.
For Technotip, e is the first vowel, so the position is 2.
For any input which do not have a vowel in it, the above javascript program outputs this statement: No vowel found in the entered string

Roots of Quadratic Equation: JavaScript

Quadratic Equations are of the form ax2 + bx + c = 0. To find roots(root1 and root2) of such an equation, we need to use the formula

quadratic-equation


Video Explaining The JavaScript Code To Find Roots of a Quadratic Equation:


YouTube Link: http://www.youtube.com/watch?v=Td6QViKdbZU [Watch the Video In Full Screen.]




To calculate the roots of a quadratic equation using a computer program, we need to break down the formula and calculate smaller parts of it and then combine to get the actual solution.

So lets calculate square root of b2 – 4 * a * c and store it in variable root_part. Also store 2 * a in variable denom. Now calculate ( – b + root_part ) / denom and store it in root1 and ( – b – root_part ) / denom in root2.
Output the values of root1 and root2 to the browser using document.write statement.

Javascript Coding Explained In Above Video:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 
<html>
 <head><title>Quadratic Equation</title></head>
 <body>
 
	<script type="text/javascript">
	<!--
		var a = prompt("Enter value of a","1");
		var b = prompt("Enter value of b","4");
		var c = prompt("Enter value of c","4");
 
		var root_part = Math.sqrt(b * b - 4 * a * c);
		var denom = 2 * a;
 
		var root1 = ( -b + root_part ) / denom;
		var root2 = ( -b - root_part ) / denom;
 
		document.write("1st root: "+root1+"<br />");
		document.write("2nd root: "+root2+"<br />");
 
	// -->
	</script>
 
 </body>
</html>

Usually people will make mistake in this line

var root_part = Math.sqrt(b * b - 4 * a * c);

Be sure that, you write capital letter M in Math.sqrt.

Work Space:
Quadratic Equation: ax2 + bx + c = 0
Let,
a = 1
b = 4
c = 4
i.e., 1x2 + 4x + 4 =0
=> 1x2 + 2x + 2x + 4 = 0
=> x ( x + 2 ) + 2 ( x + 2 ) = 0
=> ( x + 2 ) + ( x + 2 ) = 0
=> x + 2 = 0 AND x + 2 = 0
=> x = -2 AND x = -2

Generating Fibonacci Series using JavaScript

Today lets see how to generate Fibonacci Series using JavaScript programming.

First Thing First: What Is Fibonacci Series ?
Fibonacci Series is a series of numbers where the first two Fibonacci numbers are 0 and 1, and each subsequent number is the sum of the previous two. Its recurrence relation is given by Fn = Fn-1 + Fn-2.

Below are a series of Fibonacci numbers(10 numbers):
0
1
1
2
3
5
8
13
21
34

How Its Formed:
0 <-- First Number 1 <-- Second Number 1 <-- = 1 + 0 2 <-- = 1 + 1 3 <-- = 2 + 1 5 <-- = 3 + 2 8 <-- = 5 + 3 13 <-- = 8 + 5 21 <-- = 13 + 8 34 <-- = 21 + 13

Video Explaining The JavaScript Code To Generate Fibonacci Series:


Some points to keep in mind:
1. In Javascript, it is not mandatory to declare a variable before using it. But still its a good practice to declare it before using.
2. Using html comments inside javascript code ensures that, the old browsers which do not support javascript will ignore all the code written inside the script tags.
3. If we give a very large number while entering the limit, then the loop start executing and the browser memory will soon exhaust and the browser may stop responding.
4. You can use any valid html coding inside document.write statement, as the output will be then processed by a html browser.

JavaScript Code Shown In Above Video:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<html>
 <head><title>Fibonacci Series</title></head>
 <body>
	<script type="text/javascript">
	<!--
 
		var var1 = 0;
		var var2 = 1;
		var var3;
 
		var num = prompt("Enter the limit to generate fibonacci no",0);
 
		document.write(var1+"<br />");
		document.write(var2+"<br />");
 
		for(var i=3; i <= num;i++)
		{
			var3 = var1 + var2;
			var1 = var2;
			var2 = var3;
 
			document.write(var3+"<br />");
		}
 
	// -->
	</script>
 
 </body>
</html>

In JavaScript:
Variable declaration is done using var keyword, followed by the variable name.
document.write is the output statement.
prompt is used to get the input from the user.

Even though the above program is easy, you may forget the logic when it is needed. So don’t forget to actually pullout a text editor and try it out yourself.