-->

Monday, April 6, 2015

How to change background-color of element using Java Script

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div#box1
{
    background-color : Gray;
    height:200px;
    width : 200px;
}


</style>
<script type ="text/javascript">
    function backcolo(ele, clr) {

        var elem = document.getElementById(ele);
        elem.style.transition = "background 1.0s linear 0s";
        elem.style.background = clr;

    }

</script>

    <title>Change Background color</title>
</head>
<body>
<button onclick="backcolo('box1','Red');"> Red Color</button>

<button onclick="backcolo('box1','green');"> Green Color</button>

<button onclick="backcolo('box1','orange');"> orange Color</button>

<div id="box1">Paste your content here</div>
</body>
</html>

Code generate the following code

How to change background-color of element using Java Script How to change background-color of element using Java Script
How to change background-color of element using Java Script change background color of element

Object properties and Methods in Java Script

These objects all have particular properties and methods that are associated with their respective objects and they can be accessed and manipulated. A property of an object is a predefined variable that you can assign a value to with simple dot notation syntax like this:

objectNamePropertyName = value

For instance, if you want to change background color of document object to yellow, you would access the bgColor property and assign the String “yellow” to it like this:

Document.bgcolor=”yellow”

A Method of an Object is just a predefined function that has already been assigned to an Object by Netscape. You invoke a Method on an Object with same dot notation like this.

objectName.methodName( )

Window Object is the parent object of all other objects In a page, which means it’s at the top of the hierarchy of all page content, including those that have FRAMESETs and FRAMEs. All other objects are its descendants or child objects. Some of the child objects like the document object are also parent or container objects for other objects that are lower down in the hierarchy. All child objects are said to be properties of their respective parent objects and such they can be manipulated and referenced with java script.
Suppose you want to give focus to window at some point in script. You do that by referencing the window object and calling the focus( ) method like this

Window.focus( );

Window object is always the parent object, Netscape allows you to omit it from expression that invoke other objects, since it is always assumed to be there.

Function in Java Script

A function is a process that incorporates a sequence of java script statement to accomplish a task. To integrate a function into document you have to first define it within a SCRIPT, which is contained in the in the head element. Then you have to call function. Calling the function can be accomplished in several ways, including the ability to call a function from within another function. In many instances function is called as the value of an event handler of an HTML element, which is called attribute assignment. The simplest way to call a function is to use it by name as statement. You can use the return statement to return a value with a function. It’s usually a good idea to define functions in the head of document so that functions are loaded first, before any of the HTML elements in the body have loaded. This precludes the generation of many java script runtime errors due to a script in one part of document trying to interact with another script that hasn’t loaded yet. This occurs when the user tries to click a button object before the page fully loads, and button needs that unloaded code before it will work. Since that required code hasn’t loaded yet, you get a runtime error. There are exceptions to HEAD Scripts.

Defining a function with function statement

Defining a function starts by using function keywords, which is followed by the name of function and then a comma-separated list of arguments that are enclosed within parentheses. You can define a function that takes no arguments, but you still have to include the parentheses. Next comes a sequence of Statements that are semicolon separated and enclosed within curly braces {}. The following function setColor() takes no Argument and sets the background color to blue when it is called.

Function setColor()
{
document.bgcolor=”blue”;

Syntax:

Function functionName(argument1, argument 2,………,argument)
{
Statement 1;
Statement 2;
}

Calling a function by attribute assignment

Defining a function is the first step in getting a function to execute its Statements. Next you have to call function within a SCRIIPT or you have to assign it to an event handler of an html element, which is shown in the following example:
To start the process for this scenario you could code previously defined setColor() function so that it was more useful by adding a color Argument to it like this.

Function setColor(color)
{
Document.bgcolor=color;
}

So that when setColor() function is called, background will be changed to color argument that is provided at that time, which can be different each time function is called. For instance, suppose you define three button Objects that each have setColor() function assigned to its respective onClick Event Handler, like this:

<input type=”button” value=”red it” onClick=”setColor(‘red’);”>
<input type=”button” value=”blue it” onClick=”setColor(‘blue’);”>
<input type=”button” value=”green it” onClick=”setColor(‘green’);”>

Then, if the user clicks on the first button, setColor() function uses String ‘red’ as the color argument to change the background color to red. If the user clicks on the second Button, the onClick Event Handler uses the same setColor() function but has a different String value to provide as the color argument so that the background color gets changed to blue. The same is true for the button with ‘green’ as the color argument.

Example of inline scripts in java script

When scripts are executed from top to bottom, means your script appear in both <head> as well as <body> section. No one scripts is executed inside the tag known as inline scripts. Let’s take a simple example.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" >
    alert("Hello");

</script>
    <title></title>
</head>
<body>
<script type="text/javascript" >
    alert("World!");

</script>
</body>
</html>

Code Generate the following output

Example of inline scripts in java script

Example of inline scripts in java script

How to print date in Java Script

Date object enables Java Script programmers to create an object that contains information about a particular date and provides a set of methods to work with that information. To create an instance of the date object, use the keyword new as follows:
var my_date = new Date(parameters);
The parameter, if left empty, indicates today's date & time . The parameter could be any specific date format.

Date object provides the following methods.

getDate( ) : Returns date of the month as an integer from 1 to 31.
setDate( ) : Sets date of the month based on an integer argument from 1 to 31.
getHours( ) : Returns hours as an integer from 0 to 23.
setHours( ) : Sets hours based on an argument from 0 to 23.
getTime( ) : Returns number of milliseconds since 1 feb 2014 at 00:00:00
setTime( ) : Sets time based on an argument representing the number of Milliseconds since 1 feb 2014 at 00:00:00.

Date class gives the current date. You can take Date class object in a single variable like

Var today= new Date();


This object represent the current date. You know very well that every line of code in java script is known as statement. Lets take an simple example

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
<script type ="text/javascript" >
    var todaydate = new Date();
    document.write("Date is" + todaydate.toString());

</script>
</body>
</html>

Code generate the following output
How to print date in Java Script

Operators and Expressions in Java Script

An operator is used to transform one or more values into a single resultant value. The values to which the operator is applied is referred to as operands. A combination of an operator and its operands is referred to as an expression . This is the value that results when an operator is applied to its operands.
1. Arithmetic Operators
Arithmetic operators are the familiar operators because they are used every day to solve common math calculations. The arithmetic operators that JavaScript supports are:

Operator
Description
+
Addition
-
Subtraction or Unary negation
*
Multiplication
/
Division
%
Modulus
++
Returns the value then Increment
--
Return the value then Decrement

2. Logical Operators:
Logical operators are used to perform Boolean operators on Boolean operands and, or, not. The logical operators supported by Java Script are:
Operator
Description
||
Logical Or
&&
Logical and
!
Logical not

3. The comparison operators
Comparison operators are used to compare two values, supported by JavaScript are:
Operator
Description
==
Equal
===
Strictly Equal
!=
Not Equal
!==
Strictly Not Equal
< 
Less than
<=
Less than or equal to
> 
Greater than
>=
Greater than or equal to

4. String Operators
String operators are those operators that are used to perform operations on strings JavaScript supports only the string concatenation (+) operator.
This operator is used to join two string. Eg. "xy" + "cd" produce "xycd".

5. Assignment Operator
Assignment operator is used to update the value of a variable. Few assignment operators are combined with other operators to perform a computation on the value contained in a variable and then update the variable with the new value.

6. Conditional Expression Ternary Operator 
JavaScript supports conditional expression operator. They are ? and : the conditional expression operator is a ternary operator since it take three operands, a condition to be evaluated and two alternative values to be returned based on the truth or falsity of the condition.
Syntax

condition ? value 1: value ?

The condition expressed must return a value true or false. If the condition is true, value 1 is the result of the expression, otherwise value 2 is the result of the expression.

7. Special Operators
Java Script supports a number of special operators that do not fit into operator categories covered above.
1. delete Operators:
The delete operator is used to delete a property of an element or an object at an array index.
Example

delete test[6]

Deletes the seventh element of test.
2. new operator:
new operator is used to create an instance of an object type.
Example 

test = new Array()

This will create a new JavaScript object of the type array and assign this array to a context area in memory called test.
3. void operator:
void operator does not return a value. It is typically used in Java Script to return a URL with no value.

Data Types and Literal in JavaScript

JavaScript support four primitive types of values and supports complex types such as objects and arrays. Primitive type are types that can be assigned a single literal value such as number, string or boolean value. Literal are fixed values, which literally provide a value in a program.

The Primitive data type are:

1. Number :
Consists of integer and floating point numbers and a special NaN (not a number) value.
Integer Literals can be represented in JavaScript in decimal, hexadecimal, and octal form .
Floating-point literals are used to represent numbers that require the use of a decimal point, or very large or very small numbers that must be written using exponential notation. A floating-point number must consist of either a number containing a decimal point or an integer followed by an exponent.
Eg : 22, 15.20, -36.7, 2E5, 0x6F

2. Boolean :
Java Script supports a pure boolean type that consists of two values true and false.
Logical operators can be used in Boolean expressions.
Java Script converts the boolean values true and false into 1 and 0 when they are used in numerical expressions.

3. String :
consists of string values that are enclosed in double or single quotes.
Java Script provides built-in support for strings. A string is a sequence of Zero or more characters that are enclosed by double(") or single (') quotes. If a string begins with a double it must end-with a double quote. If a string begins with a single quote it must end with a single quote.
Eg : "james", '2, USA'

4. Null :
Null value is common to all JavaScript types. It is used to set a variable to an initial value that is different from other valid values. Use of the null value prevents the sort of errors that results from using uninitialized variables. Null value is automatically converted to default values of other types when used in an expression.

5. Type Casting :
In Java Script variables are loosely cast. The type of a Java Script variable is implicitly based on the literal values that are assigned to it from time to time.
For instance, combining the string literal " Total amount is " with the integer literal 1000 results in a string with the value "total amount is 1000" . Adding together the literal 10.5 and the string "20" results in the floating point integer literal 30.5. This process is known as type casting.

Casting Variables
In other to make working with data types convenient, variables are created . In Java Script variables can be created that can hold any type of data.
Declaring a variable tells JavaScript that a variable of a given name exists so that the Java Script interpreter can understand references to that variable name throughout the rest of the script.
Although it is possible to declare variables by simply using them, declaring variables helps to ensure that programs are well organized and helps keep track of the scope of the variables. Variables can be declared using var command.
Syntax

var <variable name:> = value ;

Example :
var first_name;
var last_name="jacob";

The equal sign (=) used in assigning a value to variable is known as an assignment operator.
92J5UZPS8GTE
© Copyright 2013 Computer Programming | All Right Reserved