37
Java Script Lectured By: Vivek Dimri Asst. Professor, SET, Sharda University

Lectured By: Vivek Dimri Asst. Professor, SET, Sharda University

Embed Size (px)

Citation preview

Java Script

Java ScriptLectured By:Vivek DimriAsst. Professor, SET, Sharda UniversityWhat is Java ScriptJavaScript is a client-side scripting language.A scripting language is a lightweight programming language.JavaScript is programming code that can be inserted into HTML pages.JavaScript inserted into HTML pages, can be executed by all modern web browsers. Java Script can enhance the dynamics and interactive features of your page by allowing you to perform calculations, check forms, write interactive games, add special effects, customize graphics selections, create security passwords and more.Lectured by: Vivek DimriWhat is Java ScriptJavaScript is used in Web site development to such things as:automatically change a formatted date on a Web pagecause a linked-to-page to appear in a popup windowcause text or a graphic image to change during a mouse rolloverLectured by: Vivek DimriJava Vs Java ScriptLectured by: Vivek DimriRequires the JDK to create the applet Requires a Java virtual machine to run the appletApplet files are distinct from the XHTML codeSource code is hidden from the userPrograms must be saved as separate files and compiled before they can be runPrograms run on the server sideRequires a text editorRequired a browser that can interpret JavaScript codeJavaScript can be placed within HTML and XHTMLSource code is made accessible to the userPrograms cannot write content to the hard diskPrograms run on the client side

ECMA ScriptThe responsibility for the development of a scripting standard has been transferred to an international body called the European Computer Manufacturers Association (ECMA).The standard developed by the ECMA is called ECMAScript, though browsers still refer to it as JavaScript.The latest version is ECMA-262, which is supported by the major browsers.

Lectured by: Vivek DimriWriting a Java Script ProgramThe Web browser runs a JavaScript program when the Web page is first loaded, or in response to an event.JavaScript programs can either be placed directly into the HTML file or they can be saved in external files.placing a program in an external file allows you to hide the program code from the usersource code placed directly in the HTML file can be viewed by anyoneLectured by: Vivek DimriWriting a Java Script ProgramA JavaScript program can be placed anywhere within the HTML file.Many programmers favor placing their programs between tags in order to separate the programming code from the Web page content and layout.Some programmers prefer placing programs within the body of the Web page at the location where the program output is generated and displayed.Lectured by: Vivek DimriHow to use/implement Java Script???We can implement Java script in our web page by following three ways-Inside the head tagWithin the body tagIn an external file (with extension .js)Lectured by: Vivek DimriImplementing Java ScriptInside HEAD Tag:Syntax:

Lectured by: Vivek DimriImplementing Java ScriptWithin BODY Tag:Syntax:

Lectured by: Vivek DimriImplementing Java ScriptIn an External Link:Syntax:

Myscript.js:Function msg() { alert("Hello") }Lectured by: Vivek DimriJava Script Syntax IssueJavaScript commands and names are case sensitive.JavaScript command lines end with a semicolon to separate it from the next command line in the program.in some situations, the semicolon is optionalsemicolons are useful to make your code easier to follow and interpret

Lectured by: Vivek DimriDisplaying some text on web PageYou can write on page by using following statement of Java script-document.write(message)document.writeln(message)

Example:document.write(My first message ) ;

Lectured by: Vivek DimriWorking with Variables & DataA variable is a named element in a program that stores information. The following restrictions apply to variable names:the first character must be either a letter or an underscore character ( _ )the remaining characters can be letters, numbers, or underscore charactersvariable names cannot contain spacesVariable names are case-sensitive.document.write(Year);

Lectured by: Vivek DimriTypes of VariablesJavaScript supports four different types of variablesNumeric variables can be a number, such as 13, 22.5, or -3.14159string variables is any group of characters, such as Hello or Happy Holidays!Boolean variables are variables that accept one of two values, either true or falsenull variables is a variable that has no value at all

Lectured by: Vivek DimriDeclaring a VariableBefore you can use a variable in your program, you need to declare a variable using the var command or by assigning the variable a value.Any of the following commands is a legitimate way of creating a variable named Month:var Month;var Month = December;Month = December;

Lectured by: Vivek DimriWorking with DatesThere are two ways to create a date object:variable = new Date(month day, year, hours:minutes: seconds) variable = new Date(year, month, day, hours, minutes, seconds)variable is the name of the variable that contains the date informationmonth, day, year, hours, minutes, and seconds indicate the date and timevar Today=new Date(October 15, 2006);var Today=new Date(2006, 9, 15);Lectured by: Vivek DimriJava Script Date MethodsLectured by: Vivek Dimri

Operators in JavaScriptFollowing operators are used in JavaScript-Arithmetic OperatorComparison Operator

Lectured by: Vivek DimriOperators in JavaScriptFollowing operators are used in JavaScript-Arithmetic Operator

Lectured by: Vivek DimriOperatorMeaningExample+Addition2 + 4-Subtraction6 - 2*Multiplication5 * 3/Division15 / 3%Modulus43 % 10Example

Lectured by: Vivek DimriOutputtwo plus ten = 12ten * ten = 100ten / two = 5Lectured by: Vivek DimriOperators in JavaScriptComparison Operator

Lectured by: Vivek DimriOperatorMeaningExampleResult== Equal Tox == yfalse!= Not Equal Tox != ytrue< Less Thanx < y true>Greater Thanx > y false= y falseBuilt-in JavaScript FunctionsFunctions provided by the language and you cannot change them to suit your needs.Some of the built-in functions in JavaScript are shown here:eval - eval(expr)eval evaluates the expression or statementsisFiniteDetermines if a number is finiteisNaNDetermines whether a value is Not a NumberparseIntConverts string literals to integers, no number NaN.parseFloatFinds a floating-point value at the beginning of a string.

Lectured by: Vivek DimriThe Math Object & Math MethodsAnother way of performing a calculation is to use the JavaScript built-in Math methods.These methods are applied to an object called the Math object.The syntax for applying a Math method is:value = Math.method(variable);For example, AbsValue = Math.abs(NumVar);

Lectured by: Vivek DimriThe Math Object & Math MethodsLectured by: Vivek Dimri

JavaScript FunctionsA function is a block of organized reusable code (a set of statements) for performing a single or related action.Begins with keyword function and the function name and ( )Inside the parenthesesWe can pass parameters to the functionE.g. function myfuc(arg1, arg2) {}Built-in and user-defined functions

Lectured by: Vivek DimriCreating JavaScript FunctionsDeclaration SyntaxFunctions are declared using the function reserved wordThe return value is not declared, nor are the types of the arguments

function function_name(parameters) { JavaScript commands}parameters are the values sent to the function (note: not all functions require parameters){ and } are used to mark the beginning and end of the commands in the function.

Lectured by: Vivek DimriCreating JavaScript Functions: Example

Hello World);}// - ->

Lectured by: Vivek DimriEvent in JavaScriptJavaScript is its ability to help you create dynamic web pages that increase user interactionThe building blocks of an interactive web page is the JavaScript event system. An event in JavaScript is something that happens with or on the webpage. A few example of events: A mouse clickThe webpage loadingMousing over a hot spot on the webpage, also known as hoveringSelecting an input box in an HTML formA keystroke

Lectured by: Vivek DimriEvent in JavaScriptJS Event HandlerOnclickonMouseOveronMouseOutonLoadonUnload, etcLectured by: Vivek DimriJavaScript ObjectObjectNumberStringDateArrayBooleanMath, etcLectured by: Vivek DimriWindow Document ObjectThe Window object represents a web browser window. In client-side JavaScript, the Window object is the global object that defines all top-level properties and methods. The properties and methods of the Window object are therefore global properties and global functions and you can refer to them by their property names without any object prefix. One of the properties of the Window object is named window and refers back to the Window object itself:window // The global Window object window.document // The document property of the window document // Or omit the object prefixLectured by: Vivek DimriBrowser Document ObjectLectured by: Vivek Dimri

Document ObjectJava script enable browsers are capable of recognizing individual objects in a HTML page.Each HTML document loaded into a browser window becomes a Document object.The Document object provides access to all HTML elements in a page, from within a script.DOM has following properties-Anchor AppletBodyCookiesFormImageLinkTitle URL , etc

Lectured by: Vivek DimriDocument ObjectDOM methods-Open()Close()getElementByName()getElementBYId()Write()Writeln()Lectured by: Vivek DimriValidation in JavaScriptForm Validation-Form data that typically are checked by a JavaScript could be:has the user left required fields empty?has the user entered a valid e-mail address?has the user entered a valid date?has the user entered text in a numeric field?Ex:Blank/ or null validationvar x= document.forms["myForm"]["fname"].value if (x==null || x=="") // for Null or blank valueEmail validationvar x=document.forms["myForm"]["email"].value;var atpos=x.indexOf("@");var dotpos=x.lastIndexOf(".");if (atpos