Knowledge in Java

JavaScript Can Change HTML Styles (CSS)

JavaScript Can Change HTML Styles (CSS)Changing the style of an HTML element, is a variant of changing an HTML attribute:Exampledocument.getElementById("demo").style.fontSize = "35px";JavaScript Can Hide HTML ElementsHiding HTML elements can be done by changing the display style:Exampledocument.getElementById("demo").style.display = "none";JavaScript Can Show HTML ElementsShowing hidden HTML elements can also be done by changing the display style:Exampledocument.getElementById("demo").style.display = "block";

JavaScript Introduction

JavaScript Can Change HTML ContentOne of many JavaScript HTML methods is getElementById().This example uses the method to "find" an HTML element (with id="demo") and changes the element content (innerHTML) to "Hello JavaScript":Exampledocument.getElementById("demo").innerHTML = "Hello JavaScript";JavaScript accepts both double and single quotes:Exampledocument.getElementById('demo').innerHTML = 'Hello JavaScript';

JavaScript Can Change HTML Styles (CSS)

JavaScript Can Change HTML Styles (CSS)JavaScript Can Change HTML Styles (CSS)Changing the style of an HTML element, is a variant of changing an HTML attribute:Exampledocument.getElementById("demo").style.fontSize = "35px";JavaScript Can Hide HTML ElementsHiding HTML elements can be done by changing the display style:Exampledocument.getElementById("demo").style.display = "none";JavaScript Can Show HTML ElementsShowing hidden HTML elements can also be done by changing the display style:Exampledocument.getElementById("demo").style.display = "block";

JavaScript Where To

JavaScript Where ToThe <script> TagIn HTML, JavaScript code must be inserted between <script> and </script> tags.Example<script>document.getElementById("demo").innerHTML = "My First JavaScript";</script>Old JavaScript examples may use a type attribute: <script type="text/javascript">.The type attribute is not required. JavaScript is the default scripting language in HTML.JavaScript Functions and EventsA JavaScript function is a block of JavaScript code, that can be executed when "called" for.For example, a function can be called when an event occurs, like when the user clicks a button.You will learn much more about functions and events in later chapters.JavaScript in <head> or <body>You can place any number of scripts in an HTML document.Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.JavaScript in <head>In this example, a JavaScript function is placed in the <head> section of an HTML page.The function is invoked (called) when a button is clicked:Example<!DOCTYPE html><html><head><script>function myFunction() {  document.getElementById("demo").innerHTML = "Paragraph changed.";}</script></head><body><h1>A Web Page</h1><p id="demo">A Paragraph</p><button type="button" onclick="myFunction()">Try it</button></body></html>

JavaScript Statements

JavaScript StatementsExamplevar x, y, z;    // Statement 1x = 5;          // Statement 2y = 6;          // Statement 3z = x + y;      // Statement 4JavaScript ProgramsA computer program is a list of "instructions" to be "executed" by a computer.In a programming language, these programming instructions are called statements.A JavaScript program is a list of programming statements.In HTML, JavaScript programs are executed by the web browser.JavaScript StatementsJavaScript statements are composed of:Values, Operators, Expressions, Keywords, and Comments.This statement tells the browser to write "Hello Dolly." inside an HTML element with id="demo":Exampledocument.getElementById("demo").innerHTML = "Hello Dolly.";Most JavaScript programs contain many JavaScript statements.The statements are executed, one by one, in the same order as they are written.JavaScript programs (and JavaScript statements) are often called JavaScript code.

Semicolons ;

Semicolons ;Semicolons separate JavaScript statements.Add a semicolon at the end of each executable statement:var a, b, c;     // Declare 3 variablesa = 5;           // Assign the value 5 to ab = 6;           // Assign the value 6 to bc = a + b;       // Assign the sum of a and b to cWhen separated by semicolons, multiple statements on one line are allowed:a = 5; b = 6; c = a + b;On the web, you might see examples without semicolons.Ending statements with semicolon is not required, but highly recommended.JavaScript White SpaceJavaScript ignores multiple spaces. You can add white space to your script to make it more readable.The following lines are equivalent:var person = "Hege";var person="Hege";A good practice is to put spaces around operators ( = + - * / ):var x = y + z;JavaScript Line Length and Line BreaksFor best readability, programmers often like to avoid code lines longer than 80 characters.If a JavaScript statement does not fit on one line, the best place to break it is after an operator:Exampledocument.getElementById("demo").innerHTML ="Hello Dolly!";JavaScript Code BlocksJavaScript statements can be grouped together in code blocks, inside curly brackets {...}.The purpose of code blocks is to define statements to be executed together.One place you will find statements grouped together in blocks, is in JavaScript functions:Examplefunction myFunction() {  document.getElementById("demo1").innerHTML = "Hello Dolly!";  document.getElementById("demo2").innerHTML = "How are you?";}In this tutorial we use 2 spaces of indentation for code blocks.You will learn more about functions later in this tutorial.

JavaScript Syntax

JavaScript SyntaxJavaScript syntax is the set of rules, how JavaScript programs are constructed:var x, y, z;       // How to declare variablesx = 5; y = 6;      // How to assign valuesz = x + y;         // How to compute valuesJavaScript ValuesThe JavaScript syntax defines two types of values: Fixed values and variable values.Fixed values are called literals. Variable values are called variables.JavaScript LiteralsThe most important rules for writing fixed values are:Numbers are written with or without decimals:10.501001Strings are text, written within double or single quotes:"John Doe"'John Doe'JavaScript VariablesIn a programming language, variables are used to store data values.JavaScript uses the var keyword to declare variables.An equal sign is used to assign values to variables.In this example, x is defined as a variable. Then, x is assigned (given) the value 6:var x;x = 6;JavaScript OperatorsJavaScript uses arithmetic operators ( + - * / ) to compute values:(5 + 6) * 10

JavaScript Expressions

JavaScript ExpressionsAn expression is a combination of values, variables, and operators, which computes to a value.The computation is called an evaluation.For example, 5 * 10 evaluates to 50:5 * 10Expressions can also contain variable values:x * 10The values can be of various types, such as numbers and strings.For example, "John" + " " + "Doe", evaluates to "John Doe":"John" + " " + "Doe"JavaScript KeywordsJavaScript keywords are used to identify actions to be performed.The var keyword tells the browser to create variables:var x, y;x = 5 + 6;y = x * 10;JavaScript CommentsNot all JavaScript statements are "executed".Code after double slashes // or between /* and */ is treated as a comment.Comments are ignored, and will not be executed:var x = 5;   // I will be executed// var x = 6;  I will NOT be executed

JavaScript Identifiers

JavaScript IdentifiersIdentifiers are names.In JavaScript, identifiers are used to name variables (and keywords, and functions, and labels).The rules for legal names are much the same in most programming languages.In JavaScript, the first character must be a letter, or an underscore (_), or a dollar sign ($).Subsequent characters may be letters, digits, underscores, or dollar signs.Numbers are not allowed as the first character.This way JavaScript can easily distinguish identifiers from numbers.JavaScript is Case SensitiveAll JavaScript identifiers are case sensitive. The variables lastName and lastname, are two different variables:var lastname, lastName;lastName = "Doe";lastname = "Peterson";JavaScript does not interpret VAR or Var as the keyword var.JavaScript and Camel CaseHistorically, programmers have used different ways of joining multiple words into one variable name:Hyphens:first-name, last-name, master-card, inter-city.Hyphens are not allowed in JavaScript. They are reserved for subtractions.Underscore:first_name, last_name, master_card, inter_city.Upper Camel Case (Pascal Case):FirstName, LastName, MasterCard, InterCity.Lower Camel Case:JavaScript programmers tend to use camel case that starts with a lowercase letter:firstName, lastName, masterCard, interCity.JavaScript Character SetJavaScript uses the Unicode character set.Unicode covers (almost) all the characters, punctuations, and symbols in the world.For a closer look, please study our Complete Unicode Reference.

JavaScript Variables

JavaScript variables are containers for storing data values.In this example, x, y, and z, are variables:Examplevar x = 5;var y = 6;var z = x + y;From the example above, you can expect:x stores the value 5y stores the value 6z stores the value 11Much Like AlgebraIn this example, price1, price2, and total, are variables:Examplevar price1 = 5;var price2 = 6;var total = price1 + price2;In programming, just like in algebra, we use variables (like price1) to hold values.In programming, just like in algebra, we use variables in expressions (total = price1 + price2).From the example above, you can calculate the total to be 11.

JavaScript Identifiers

JavaScript IdentifiersAll JavaScript variables must be identified with unique names.These unique names are called identifiers.Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).The general rules for constructing names for variables (unique identifiers) are:Names can contain letters, digits, underscores, and dollar signs.Names must begin with a letterNames can also begin with $ and _ (but we will not use it in this tutorial)Names are case sensitive (y and Y are different variables)Reserved words (like JavaScript keywords) cannot be used as namesJavaScript identifiers are case-sensitive.The Assignment OperatorIn JavaScript, the equal sign (=) is an "assignment" operator, not an "equal to" operator.This is different from algebra. The following does not make sense in algebra:x = x + 5In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)The "equal to" operator is written like == in JavaScript.JavaScript Data TypesJavaScript variables can hold numbers like 100 and text values like "John Doe".In programming, text values are called text strings.JavaScript can handle many types of data, but for now, just think of numbers and strings.Strings are written inside double or single quotes. Numbers are written without quotes.If you put a number in quotes, it will be treated as a text string.Examplevar pi = 3.14;var person = "John Doe";var answer = 'Yes I am!';Declaring (Creating) JavaScript VariablesCreating a variable in JavaScript is called "declaring" a variable.You declare a JavaScript variable with the var keyword:var carName;After the declaration, the variable has no value (technically it has the value of undefined).To assign a value to the variable, use the equal sign:carName = "Volvo";You can also assign a value to the variable when you declare it:var carName = "Volvo";In the example below, we create a variable called carName and assign the value "Volvo" to it.Then we "output" the value inside an HTML paragraph with id="demo":Example<p id="demo"></p><script>var carName = "Volvo";document.getElementById("demo").innerHTML = carName;</script>

One Statement, Many Variables

One Statement, Many VariablesYou can declare many variables in one statement.Start the statement with var and separate the variables by comma:var person = "John Doe", carName = "Volvo", price = 200;A declaration can span multiple lines:var person = "John Doe",carName = "Volvo",price = 200;Value = undefinedIn computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input.A variable declared without a value will have the value undefined.The variable carName will have the value undefined after the execution of this statement:Examplevar carName;Re-Declaring JavaScript VariablesIf you re-declare a JavaScript variable, it will not lose its value.The variable carName will still have the value "Volvo" after the execution of these statements:Examplevar carName = "Volvo";var carName;JavaScript ArithmeticAs with algebra, you can do arithmetic with JavaScript variables, using operators like = and +:Examplevar x = 5 + 2 + 3;You can also add strings, but strings will be concatenated:Examplevar x = "John" + " " + "Doe";Also try this:Examplevar x = "5" + 2 + 3;