HTML coding

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

JS Operators

JavaScript Operators « PreviousNext Chapter » = is used to assign values, + is used to add values, ++ is used to increment values. The assignment operator = is used to assign values to JavaScript variables. The arithmetic operator + is used to add values together. Example Assign values to variables and add them together: y = 5; // assign the value 5 to y z = 2; // assign the value 2 to z x = y + z; // assign the value 7 (y + z) to x The result of x will be: 7 Try it Yourself » JavaScript Arithmetic Operators Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y = 5, the table below explains the arithmetic operators: Operator Description Example Result Result Try it + Addition x = y + 2 y = 5 x = 7 Try it » - Subtraction x = y - 2 y = 5 x = 3 Try it » * Multiplication x = y * 2 y = 5 x = 10 Try it » / Division x = y / 2 y = 5 x = 2.5 Try it » % Modulus (division remainder) x = y % 2 y = 5 x = 1 Try it » ++ Increment x = ++y y = 6 x = 6 Try it » x = y++ y = 6 x = 5 Try it » -- Decrement x = --y y = 4 x = 4 Try it » x = y-- y = 4 x = 5 Try it » JavaScript Assignment Operators Assignment operators are used to assign values to JavaScript variables. Given that x = 10 and y = 5, the table below explains the assignment operators: Operator Example Same As Result Try it = x = y x = y x = 5 Try it » += x += y x = x + y x = 15 Try it » -= x -= y x = x - y x = 5 Try it » *= x *= y x = x * y x = 50 Try it » /= x /= y x = x / y x = 2 Try it » %= x %= y x = x % y x = 0 Try it » JavaScript String Operators The + operator can also be used to concatenate (add) strings. Note When used on strings, the + operator is called the concatenation operator. Example To add two or more string variables together, use the + operator. txt1 = "What a very"; txt2 = "nice day"; txt3 = txt1 + txt2; The result of txt3 will be: What a verynice day Try it Yourself » To add a space between the two strings, insert a space into one of the strings: Example txt1 = "What a very "; txt2 = "nice day"; txt3 = txt1 + txt2; The result of txt3 will be: What a very nice day Try it Yourself » or insert a space into the expression: Example txt1 = "What a very"; txt2 = "nice day"; txt3 = txt1 + " " + txt2; The result of txt3 will be: What a very nice day Try it Yourself » The += operator can also be used to concatenate strings: Example txt1 = "What a very "; txt1 += "nice day"; The result of txt1 will be: What a very nice day Try it Yourself » Adding Strings and Numbers Adding two numbers, will return the sum, but adding a number and a string will return a string: Example x = 5 + 5; y = "5" + 5; z= "Hello" + 5; The result of x, y, and z will be: 10 55 Hello5 Try it Yourself » The rule is: If you add a number and a string, the result will be a string! JavaScript Bitwise Operators Bit operators work on 32 bits numbers. Any numeric operand in the operation is converted into a 32 bit number. The result is converted back to a JavaScript number. Example x = 5 & 1; The result in x: 1 Try it Yourself » Operator Description Example Same as Result Decimal & AND x = 5 & 1 0101 & 0001 0001 1 | OR x = 5 | 1 0101 | 0001 0101 5 ~ NOT x = ~ 5 ~0101 1010 10 ^ XOR x = 5 ^ 1 0101 ^ 0001 0100 4 << Left shift x = 5 << 1 0101 << 1 1010 10 >> Right shift x = 5 >> 1 0101 >> 1 0010 2 Note The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit signed numbers. Because of this, in JavaScript, ~ 5 will not return 10. It will return -6. ~00000000000000000000000000000101 will return 11111111111111111111111111111010 The typeof operator The typeof operator returns the type of a variable (or an expression): Example var x = 5; var y = "John"; typeof x // Returns number typeof y // Returns string typeof 3.14 // Returns number typeof false // Returns boolean typeof [1,2,3,4] // Returns object typeof {name:'john', age:34} // Returns object Try it yourself » The delete Operator The delete operator can be used to delete properties from objects: Example var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; delete person.age; The delete operator is designed to be used on object properties. It has no effect on variables or functions. The delete operator should not be used on predefined JavaScript object properties. It can crash your application. The Unary + Operator The unary + operator can be used to convert a variable to a number: Example var y = "5"; // y is a string var x = + y; // x is a number Try it yourself » If the variable cannot be converted, it will still become a number, but with the value NaN (Not a number): Example var y = "John"; // y is a string var x = + y; // x is a number (NaN) Try it yourself »

JS comments

JavaScript Comments Not all JavaScript statements are "commands". Anything after double slashes // is ignored by the browser: // I will not be executed

JS Strings

JavaScript Strings « PreviousNext Chapter » JavaScript strings are used for storing and manipulating text. JavaScript Strings A JavaScript string simply stores a series of characters like "John Doe". A string can be any text inside quotes. You can use single or double quotes: Example var carname = "Volvo XC60"; var carname = 'Volvo XC60'; You can use quotes inside a string, as long as they don't match the quotes surrounding the string: Example var answer = "It's alright"; var answer = "He is called 'Johnny'"; var answer = 'He is called "Johnny"'; Or you can put quotes inside a string by using the \ escape character: Example var answer = 'It\'s alright'; var answer = "He is called \"Johnny\""; Try it yourself » String Length The length of a string (a string object) is found in the built in property length: Example var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; var sln = txt.length; Try it Yourself » Special Characters In JavaScript, strings are written as characters inside single or double quotes. Because of this, JavaScript will misunderstand this string: "We are the so-called "Vikings" from the north." The string will be chopped to "We are the so-called ". To solve this problem, you can place a backslash (\) before the double quotes in "Vikings": "We are the so-called \"Vikings\" from the north." The backslash is an escape character. Escape characters turns special characters into string characters: The escape character (\) can be used to insert apostrophes, new lines, quotes, and other special characters into a string. The table below lists other special characters that can be added to a text string with the backslash sign: Code Outputs \' single quote \" double quote \\ backslash \n new line \r carriage return \t tab \b backspace \f form feed Strings Can be Objects Normally, JavaScript strings are primitive values, created from literals: var firstName = "John" But strings can also be defined as objects with the keyword new: var firstName = new String("John") Example var x = "John"; var y = new String("John"); // type of x will return String // type of y will return Object Try it yourself » Note Don't create String objects. They slow down execution speed, and produce nasty side effects: Example var x = "John"; var y = new String("John"); // (x === y) is now false because x is a string and y is an object. Try it yourself » String Properties and Methods Primitive values, like "John Doe", cannot have properties or methods (because they are not objects). But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties. String methods are covered in next chapter. String Properties Property Description constructor Returns the function that created the String object's prototype length Returns the length of a string prototype Allows you to add properties and methods to an object String Methods Method Description charAt() Returns the character at the specified index (position) charCodeAt() Returns the Unicode of the character at the specified index concat() Joins two or more strings, and returns a copy of the joined strings fromCharCode() Converts Unicode values to characters indexOf() Returns the position of the first found occurrence of a specified value in a string lastIndexOf() Returns the position of the last found occurrence of a specified value in a string localeCompare() Compares two strings in the current locale match() Searches a string for a match against a regular expression, and returns the matches replace() Searches a string for a value and returns a new string with the value replaced search() Searches a string for a value and returns the position of the match slice() Extracts a part of a string and returns a new string split() Splits a string into an array of substrings substr() Extracts a part of a string from a start position through a number of characters substring() Extracts a part of a string between two specified positions toLocaleLowerCase() Converts a string to lowercase letters, according to the host's locale toLocaleUpperCase() Converts a string to uppercase letters, according to the host's locale toLowerCase() Converts a string to lowercase letters toString() Returns the value of a String object toUpperCase() Converts a string to uppercase letters trim() Removes whitespace from both ends of a string valueOf() Returns the primitive value of a String object

How to create a floating thumb nail

.thumbnail { float: left; width: 110px; height: 90px; margin: 5px; }

How do you create comments?

<!-- This is a comment -->

Script tag

<script> </script>

JS Conventions

JavaScript Coding Conventions « PreviousNext Chapter » Always use the same coding conventions for all your JavaScript projects. Coding Conventions Coding conventions are style guidelines for programming. They typically cover: Naming and declaration rules for variables and functions. Rules for the use of white space, indentation, and comments. Programming practices and principles Coding conventions secure software quality: Improves code readability Make code maintenance easier Coding conventions can be documented rules for teams to follow, or just be your individual coding practice. Note This page describes the general JavaScript code conventions used by W3Schools. You should also read the next chapter "Best Practices", and learn how to avoid coding pitfalls. Variable Names At W3schools we use camelCase for identifier names (variable and function). All names start with a letter. At the bottom of this page, you will find a wider discussion about naming rules. firstName = "John"; lastName = "Doe"; price = 19.90; discount = 0.10; fullPrice = price * 100 / discount; Declarations on Top It is good coding practice to put all declarations at the top of each script or function. This gives better, cleaner code, and reduces the possibility of accidental re-declarations. var firstName, lastName; var price, discount, fullPrice; firstName = "John"; lastName = "Doe"; price = 19.90; discount = 0.10; fullPrice = price * 100 / discount; This also goes for variables in loops: var i; for (i = 0; i < 5; i++) Note Since JavaScript moves the declarations to the top anyway (JavaScript hoisting), it is always a good rule. Spaces Around Operators Always put spaces around operators, and after commas: x = 5 + 6; // Good x=5+6 // Bad [40, 100, 1, 5] // Good [40,100,1,5] // Bad Code Indentation Always use 4 spaces for indentation of code blocs: function toCelsius(fahrenheit) { return (5/9) * (fahrenheit-32); } for (i = 1; i < 50; i++) { sum += i; } Note Do not use tabs (tabulators) for indentation. Text editors interpret tabs differently. Line Length < 80 For readability, avoid 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 or a comma. Example document.getElementById("demo").innerHTML = "Hello Dolly."; Try it Yourself » Performance Coding conventions are not used by computers. Most rules have little impact on the execution of programs. Indentation and extra spaces are not significant in small scripts. For code in development, readability should be preferred. Larger production scripts should be minifyed. Naming Conventions Always use the same naming convention for all your code. For example: Variable and function names written as camelCase Global variable written in UPPERCASE Constants (like PI) written in UPPERCASE Should you use hyp-hens, camelCase, or under_scores in variable names? This is a question programmers often discuss. The answer depends on who you ask: Hyphens in HTML and CSS: HTML5 attributes can start with data- (data-quantity, data-price). CSS uses hyphens in property-names (font-size). Note Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed in JavaScript names. Underscores: Many programmers prefer to use underscores (date_of_birth), especially in SQL databases. Underscores are often used in PHP documentation. CamelCase: CamelCase is often preferred by C programmers. camelCase: camelCase is used by JavaScript itself, by jQuery, and other JavaScript libraries. Note Don't start names with a $ sign. It will put you in conflict with many JavaScript library names.

How to create a box model in CSS

div { width: 220px; padding: 10px; border: 5px solid gray; margin: 0px; }

How to create a border in CSS

p.one { border-style: solid; border-width: 5px; } p.two { border-style: solid; border-width: medium; }

How to create lists in CSS

ul { list-style-type: none; padding: 0px; margin: 0px; } ul li { background-image: url(sqpurple.gif); background-repeat: no-repeat; background-position: 0px 5px; padding-left: 14px; }

What are some properties of font sizes?

font Sets all the font properties in one declaration font-family Specifies the font family for text font-size Specifies the font size of text font-style Specifies the font style for text font-variant Specifies whether or not a text should be displayed in a small-caps font font-weight Specifies the weight of a font

Functions

function myFunction(p1, p2) { return p1 * p2; // the function returns the product of p1 and p2 } ============================================ JavaScript Functions are Objects In JavaScript, functions are objects. JavaScript functions have properties and methods. You can add your own properties and methods to functions. JavaScript Functions are Variables Too In JavaScript, functions can be used as variables: Example Instead of: temp = toCelsius(32); text = "The temperature is " + temp + " Centigrade"; You can use: text = "The temperature is " + toCelsius(32) + " Centigrade";

What are some examples of color codes?

#000000 rgb(0,0,0) #080000 rgb(8,0,0) #100000 rgb(16,0,0) #180000 rgb(24,0,0) #200000 rgb(32,0,0) #280000 rgb(40,0,0) #300000 rgb(48,0,0) #380000 rgb(56,0,0) #400000 rgb(64,0,0) #480000 rgb(72,0,0) #500000 rgb(80,0,0) #580000 rgb(88,0,0) #600000 rgb(96,0,0) #680000 rgb(104,0,0) #700000 rgb(112,0,0) #780000 rgb(120,0,0) #800000 rgb(128,0,0) #880000 rgb(136,0,0) #900000 rgb(144,0,0) #980000 rgb(152,0,0) #A00000 rgb(160,0,0) #A80000 rgb(168,0,0) #B00000 rgb(176,0,0) #B80000 rgb(184,0,0) #C00000 rgb(192,0,0) #C80000 rgb(200,0,0) #D00000 rgb(208,0,0) #D80000 rgb(216,0,0) #E00000 rgb(224,0,0) #E80000 rgb(232,0,0) #F00000 rgb(240,0,0) #F80000 rgb(248,0,0) #FF0000 rgb(255,0,0) Shades of Gray Gray colors are displayed using an equal amount of power to all of the light sources. To make it easier for you to select the right gray color we have compiled a table of gray shades for you: Gray Shades HEX RGB #000000 rgb(0,0,0) #080808 rgb(8,8,8) #101010 rgb(16,16,16) #181818 rgb(24,24,24) #202020 rgb(32,32,32) #282828 rgb(40,40,40) #303030 rgb(48,48,48) #383838 rgb(56,56,56) #404040 rgb(64,64,64) #484848 rgb(72,72,72) #505050 rgb(80,80,80) #585858 rgb(88,88,88) #606060 rgb(96,96,96) #686868 rgb(104,104,104) #707070 rgb(112,112,112) #787878 rgb(120,120,120) #808080 rgb(128,128,128) #888888 rgb(136,136,136) #909090 rgb(144,144,144) #989898 rgb(152,152,152) #A0A0A0 rgb(160,160,160) #A8A8A8 rgb(168,168,168) #B0B0B0 rgb(176,176,176) #B8B8B8 rgb(184,184,184) #C0C0C0 rgb(192,192,192) #C8C8C8 rgb(200,200,200) #D0D0D0 rgb(208,208,208) #D8D8D8 rgb(216,216,216) #E0E0E0 rgb(224,224,224) #E8E8E8 rgb(232,232,232) #F0F0F0 rgb(240,240,240) #F8F8F8 rgb(248,248,248) #FFFFFF rgb(255,255,255) Web Safe Colors? Some years ago, when computers supported max 256 different colors, a list of 216 "Web Safe Colors" was suggested as a Web standard, reserving 40 fixed system colors. This is not important now, since most computers can display millions of different colors, but the choice is left to you. The 216 cross-browser color palette was created to ensure that all computers would display the colors correctly when running a 256 color palette: 000000 000033 000066 000099 0000CC 0000FF 003300 003333 003366 003399 0033CC 0033FF 006600 006633 006666 006699 0066CC 0066FF 009900 009933 009966 009999 0099CC 0099FF 00CC00 00CC33 00CC66 00CC99 00CCCC 00CCFF 00FF00 00FF33 00FF66 00FF99 00FFCC 00FFFF 330000 330033 330066 330099 3300CC 3300FF 333300 333333 333366 333399 3333CC 3333FF 336600 336633 336666 336699 3366CC 3366FF 339900 339933 339966 339999 3399CC 3399FF 33CC00 33CC33 33CC66 33CC99 33CCCC 33CCFF 33FF00 33FF33 33FF66 33FF99 33FFCC 33FFFF 660000 660033 660066 660099 6600CC 6600FF 663300 663333 663366 663399 6633CC 6633FF 666600 666633 666666 666699 6666CC 6666FF 669900 669933 669966 669999 6699CC 6699FF 66CC00 66CC33 66CC66 66CC99 66CCCC 66CCFF 66FF00 66FF33 66FF66 66FF99 66FFCC 66FFFF 990000 990033 990066 990099 9900CC 9900FF 993300 993333 993366 993399 9933CC 9933FF 996600 996633 996666 996699 9966CC 9966FF 999900 999933 999966 999999 9999CC 9999FF 99CC00 99CC33 99CC66 99CC99 99CCCC 99CCFF 99FF00 99FF33 99FF66 99FF99 99FFCC 99FFFF CC0000 CC0033 CC0066 CC0099 CC00CC CC00FF CC3300 CC3333 CC3366 CC3399 CC33CC CC33FF CC6600 CC6633 CC6666 CC6699 CC66CC CC66FF CC9900 CC9933 CC9966 CC9999 CC99CC CC99FF CCCC00 CCCC33 CCCC66 CCCC99 CCCCCC CCCCFF CCFF00 CCFF33 CCFF66 CCFF99 CCFFCC CCFFFF FF0000 FF0033 FF0066 FF0099 FF00CC FF00FF FF3300 FF3333 FF3366 FF3399 FF33CC FF33FF FF6600 FF6633 FF6666 FF6699 FF66CC FF66FF FF9900 FF9933 FF9966 FF9999 FF99CC FF99FF FFCC00 FFCC33 FFCC66 FFCC99 FFCCCC FFCCFF FFFF00 FFFF33 FFFF66 FFFF99 FFFFCC FFFFFF

How to create a table in CSS

<!DOCTYPE html> <html> <head> <style> table, td, th { border: 1px solid green; } th { background-color: green; color: white; } </style> </head> <body> <table> <tr> <th>Firstname</th> <th>Lastname</th> <th>Savings</th> </tr> <tr> <td>Peter</td> <td>Griffin</td> <td>$100</td> </tr> <tr> <td>Lois</td> <td>Griffin</td> <td>$150</td> </tr> <tr> <td>Joe</td> <td>Swanson</td> <td>$300</td> </tr> <tr> <td>Cleveland</td> <td>Brown</td> <td>$250</td> </tr> </table> </body> </html>

How do you make titles?

<!DOCTYPE html> <html> <head> <title>Title of the document</title> </head> <body> The content of the document...... </body> </html>

JS Array methods

JavaScript Array Methods « PreviousNext Chapter » The strength of JavaScript arrays lies in the array methods. Converting Arrays to Strings In JavaScript, all objects have the valueOf() and toString() methods. The valueOf() method is the default behavior for an array. It returns an array as a string: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.valueOf(); Try it Yourself » For JavaScript arrays, valueOf() and toString() are equal. Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); Try it Yourself » The join() method also joins all array elements into a string. It behaves just like toString(), but you can specify the separator: Example <p id="demo"></p> <script> var fruits = ["Banana", "Orange","Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.join(" * "); </script> Try it Yourself » Popping and Pushing When you work with arrays, it is easy to remove elements and add new elements. This is what popping and pushing is: Popping items out of an array, or pushing items into an array. The pop() method removes the last element from an array: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.pop(); // Removes the last element ("Mango") from fruits Try it Yourself » The push() method adds a new element to an array (at the end): Note Remember: [0] is the first element in an array. [1] is the second. Array indexes start with 0. Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits Try it Yourself » The pop() method returns the string that was "popped out". The push() method returns the new array length. Shifting Elements Shifting is equivalent to popping, working on the first element instead of the last. The shift() method removes the first element of an array, and "shifts" all other elements one place down. Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.shift(); // Removes the first element "Banana" from fruits Try it Yourself » The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits Try it Yourself » The shift() method returns the string that was "shifted out". The unshift() method returns the new array length. Changing Elements Array elements are accessed using their index number: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[0] = "Kiwi"; // Changes the first element of fruits to "Kiwi" Try it Yourself » The length property provides an easy way to append a new element to an array: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruit Try it Yourself » Deleting Elements Since JavaScript arrays are objects, elements can be deleted by using the JavaScript operator delete: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; delete fruits[0]; // Changes the first element in fruits to undefined Try it Yourself » Note Using delete on array elements leaves undefined holes in the array. Use pop() or splice() instead. Splicing an Array The splice() method can be used to add new items to an array: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2, 0, "Lemon", "Kiwi"); Try it Yourself » The first parameter (2) defines the position where new elements should be added (spliced in). The second parameter (0) defines how many elements should be removed. The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added. Using splice() to Remove Elements With clever parameter setting, you can use splice() to remove elements without leaving "holes" in the array: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(0,1); // Removes the first element of fruits Try it Yourself » The first parameter (0) defines the position where new elements should be added (spliced in). The second parameter (1) defines how many elements should be removed. The rest of the parameters are omitted. No new elements will be added. Sorting an Array The sort() method sorts an array alphabetically: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // Sorts the elements of fruits Try it Yourself » The sort() method takes a function as parameter. The function can be used to define the sort method. Reversing an Array The reverse() method reverses the elements in an array. You can use it to sort an array in descending order: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // Sorts the elements of fruits fruits.reverse(); // Reverses the order of the elements Try it Yourself » Numeric Sort The sort() method cannot be used on a number array, because it sorts alphabetically (25 is bigger than 100). You can fix this by providing a function that returns -1, 0, or 1: Example var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a-b}); Try it Yourself » Use the same trick to sort an array descending: Example var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b-a}); Try it Yourself » Calling function(a, b) returns -1, 0, or 1, depending on the values of a and b. The arguments are provided by the sort() method when it compares two values. Example: When comparing 40 and 100, the sort() method calls function(40,100). Find the Highest (or Lowest) Value How to find the highest value in an array? Example var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b-a}); // now points[0] contains the highest value Try it Yourself » And the lowest: Example var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a-b}); // now points[0] contains the lowest value Try it Yourself » Joining Arrays The concat() method creates a new array by concatenating two arrays: Example var myGirls = ["Cecilie", "Lone"]; var myBoys = ["Emil", "Tobias","Linus"]; var myChildren = myGirls.concat(myBoys); // Concatenates (joins) myGirls and myBoys Try it Yourself » The concat() method can take any number of array arguments: Example var arr1 = ["Cecilie", "Lone"]; var arr2 = ["Emil", "Tobias","Linus"]; var arr3 = ["Robin", "Morgan"]; var myChildren = arr1.concat(arr2, arr3); // Concatenates arr1 with arr2 and arr3 Try it Yourself » Slicing an Array The slice() method slices out a piece of an array: Example var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var citrus = fruits.slice(1,3); Try it Yourself »

How do you add pictures in CSS?

body { background-image: url("img_tree.png"); background-repeat: no-repeat; background-position: right top; }

What are some attributes?

class Specifies one or more classnames for an element (refers to a class in a style sheet) id |Specifies a unique id for an element style |Specifies an inline CSS style for an element title |Specifies extra information about an element (displayed as a tool tip)

JS Type Conversation

JavaScript Type Conversion « PreviousNext Chapter » Number() converts to a Number, String() converts to a String, Boolean() converts to a Boolean. JavaScript Data Types In JavaScript there are 5 different data types that can contain values: string number boolean object function There are 3 types of objects: Object Date Array And 2 data types that cannot contain values: null undefined The typeof Operator You can use the typeof operator to find the data type of a JavaScript variable. Example typeof "John" // Returns string typeof 3.14 // Returns number typeof NaN // Returns number typeof false // Returns boolean typeof [1,2,3,4] // Returns object typeof {name:'John', age:34} // Returns object typeof new Date() // Returns object typeof function () {} // Returns function typeof myCar // Returns undefined (if myCar is not declared) typeof null // Returns object Try it yourself » Please observe: The data type of NaN is number The data type of an array is object The data type of a date is object The data type of null is object The data type of an undefined variable is undefined You cannot use typeof to define if an object is an JavaScript Array or a JavaScript Date. The constructor Property The constructor property returns the constructor function for all JavaScript variables. Example "John".constructor // Returns function String() { [native code] } (3.14).constructor // Returns function Number() { [native code] } false.constructor // Returns function Boolean() { [native code] } [1,2,3,4].constructor // Returns function Array() { [native code] } {name:'John', age:34}.constructor // Returns function Object() { [native code] } new Date().constructor // Returns function Date() { [native code] } function () {}.constructor // Returns function Function(){ [native code] } Try it yourself » You can check the constructor property to find out if an object is an Array (contains the word "Array"): Example function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; } Try it yourself » You can check the constructor property to find out if an object is a Date (contains the word "Date"): Example function isDate(myDate) { return myDate.constructor.toString().indexOf("Date") > -1; } Try it yourself » JavaScript Type Conversion JavaScript variables can be converted to a new variable and another datatype: By the use of a JavaScript function Automatically by JavaScript itself Converting Numbers to Strings The global method String() can convert numbers to strings. It can be used on any type of numbers, literals, variables, or expressions: Example String(x) // returns a string from a number variable x String(123) // returns a string from a number literal 123 String(100 + 23) // returns a string from a number from an expression Try it yourself » The Number method toString() does the same. Example x.toString() (123).toString() (100 + 23).toString() Try it yourself » In the chapter Number Methods, you will find more methods that can be used to convert numbers to strings: Method Description toExponential() Returns a string, with a number rounded and written using exponential notation. toFixed() Returns a string, with a number rounded and written with a specified number of decimals. toPrecision() Returns a string, with a number written with a specified length Converting Booleans to Strings The global method String() can convert booleans to strings. String(false) // returns "false" String(true) // returns "true" The Boolean method toString() does the same. false.toString() // returns "false" true.toString() // returns "true" Converting Dates to Strings The global method String() can convert dates to strings. String(Date()) // returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time) The Date method toString() does the same. Example Date().toString() // returns Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time) In the chapter Date Methods, you will find more methods that can be used to convert dates to strings: Method Description getDate() Get the day as a number (1-31) getDay() Get the weekday a number (0-6) getFullYear() Get the four digit year (yyyy) getHours() Get the hour (0-23) getMilliseconds() Get the milliseconds (0-999) getMinutes() Get the minutes (0-59) getMonth() Get the month (0-11) getSeconds() Get the seconds (0-59) getTime() Get the time (milliseconds since January 1, 1970) Converting Strings to Numbers The global method Number() can convert strings to numbers. Strings containing numbers (like "3.14") convert to numbers (like 3.14). Empty strings convert to 0. Anything else converts to NaN (Not a number). Number("3.14") // returns 3.14 Number(" ") // returns 0 Number("") // returns 0 Number("99 88") // returns NaN In the chapter Number Methods, you will find more methods that can be used to convert strings to numbers: Method Description parseFloat() Parses a string and returns a floating point number parseInt() Parses a string and returns an integer Converting Booleans to Numbers The global method Number() can also convert booleans to numbers. Number(false) // returns 0 Number(true) // returns 1 Converting Dates to Numbers The global method Number() can be used to convert dates to numbers. d = new Date(); Number(d) // returns 1404568027739 The date method getTime() does the same. d = new Date(); d.getTime() // returns 1404568027739 Automatic String Conversion JavaScript automatically calls the variable's toString() function when you try to output an object or a variable: document.getElementById("demo").innerHTML = myVar; // if myVar = {name:"Fjohn"} // toString converts to "[object Object]" // if myVar = [1,2,3,4] // toString converts to "1,2,3,4" // if myVar = new Date() // toString converts to "Fri Jul 18 2014 09:08:55 GMT+0200" Numbers and booleans are also converted, but this is not very visible: // if myVar = 123 // toString converts to "123" // if myVar = true // toString converts to "true" // if myVar = false // toString converts to "false"

JS Strict mode

JavaScript Use Strict « PreviousNext Chapter » "use strict"; Defines that JavaScript code should be executed in "strict mode". The "use strict" Directive The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript version 5). It is not a statement, but a literal expression, ignored by earlier versions of JavaScript. The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you cannot, for example, use undeclared variables. Note Strict mode is supported in: Internet Explorer from version 10. Firefox from version 4. Chrome from version 13. Safari from version 5.1. Opera from version 12. Declaring Strict Mode Strict mode is declared by adding "use strict"; to the beginning of a JavaScript file, or a JavaScript function. Declared at the beginning of a JavaScript file, it has global scope (all code will execute in strict mode). Declared inside a function, it has local scope (only the code inside the function is in strict mode). Global declaration: "use strict"; function testStrict(){ var x; x = 3.14; // This does not cause an error. } x = 3.14; // This causes an error. Local declaration: function testStrict(){ "use strict"; x = 3.14; // This causes an error. } x = 3.14; // This does not cause an error. The "use strict"; Syntax The syntax, for declaring strict mode, was designed to be compatible with older versions of JavaScript. Compiling a numeric literal (4 + 5;) or a string literal ("John Doe";) in a JavaScript program has no side effects. It simply compiles to a non existing variable and dies. So "use strict;" only matters to new compilers that "understand" the meaning of it. Why Strict Mode? Strict mode makes it easier to write "secure" JavaScript. Strict mode changes previously accepted "bad syntax" into real errors. As an example, in normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable. In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties. In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error. Not Allowed in Strict Mode Using a variable (property or object) without declaring it, is not allowed: x = 3.14; // This causes an error (if x has not been declared). Deleting a variable, a function, or an argument, is not allowed. var testStrict = 3.14; delete testStrict; // This causes an error. Defining a property more than once, is not allowed: var testStrict = {p1:10, p2:15, p1:20}; // This causes an error. Duplicating a parameter name is not allowed: function testStrict(param1, param1) {}; // This causes an error. Octal numeric literals and escape characters are not allowed: var testStrict = 010; // This causes an error. var testStrict = \010; // This causes an error. Writing to a read-only property is not allowed: var testObj = {}; Object.defineProperty(testObj, "x", {value:0, writable:false}); testObj.x = 3.14; // This causes an error. Writing to a get-only property is not allowed: var testObj = {get x() {return 0} }; testObj.x = 3.14; // This causes an error. Deleting an undeletable property is not allowed: delete Object.prototype; // This causes an error. The string "eval" cannot be used as a variable: var eval = 3.14; // This causes an error. The string "arguments" cannot be used as a variable: var arguments = 3.14; // This causes an error. The with statement is not allowed: with (Math){x = cos(2)}; // This causes an error. Future reserved keywords are not allowed. These are: implements interface package private protected public static yield Other Differences In function calls like f(), the this value was the global object. In strict mode, it is now undefined. For security reasons, in strict mode code, eval does not create a new variable in the scope from which it was called. With strict mode, you cannot, for example, use undeclared variables. Watch Out! Note The "use strict" directive is only recognized at the beginning of a script or a function. If you add two JavaScript files into one file, you will lose the effect of the directive in the second file.

How to create a display

h1.hidden { visibility: hidden; }

JS Arrays

avaScript Arrays « PreviousNext Chapter » JavaScript arrays are used to store multiple values in a single variable. Displaying Arrays In this tutorial we will use a script to display arrays inside a <p> element with id="demo": Example <p id="demo"></p> <script> var cars = ["Saab", "Volvo", "BMW"]; document.getElementById("demo").innerHTML = cars; </script> The first line (in the script) creates an array named cars. The second line "finds" the element with id="demo", and "displays" the array in the "innerHTML" of it. Try it Yourself Create an array, and assign values to it: Example var cars = ["Saab", "Volvo", "BMW"]; Try it Yourself » Spaces and line breaks are not important. A declaration can span multiple lines: Example var cars = [ "Saab", "Volvo", "BMW" ]; Try it Yourself » Note Don't put a comma after the last element (like "BMW",). It is inconsistent across browsers. What is an Array? An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: var car1 = "Saab"; var car2 = "Volvo"; var car3 = "BMW"; However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300? The solution is an array! An array can hold many values under a single name, and you can access the values by referring to an index number. Creating an Array Using an array literal is the easiest way to create a JavaScript Array. Syntax: var array-name = [item1, item2, ...]; Example: var cars = ["Saab", "Volvo", "BMW"]; Using the JavaScript Keyword new The following example also creates an Array, and assigns values to it: Example var cars = new Array("Saab", "Volvo", "BMW"); Try it Yourself » Note The two examples above do exactly the same. There is no need to use new Array(). For simplicity, readability and execution speed, use the first one (the array literal method). Access the Elements of an Array You refer to an array element by referring to the index number. This statement access the value of the first element in myCars: var name = cars[0]; This statement modifies the first element in cars: cars[0] = "Opel"; Note [0] is the first element in an array. [1] is the second. Array indexes start with 0. You Can Have Different Objects in One Array JavaScript variables can be objects. Arrays are special kinds of objects. Because of this, you can have variables of different types in the same Array. You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array: myArray[0] = Date.now; myArray[1] = myFunction; myArray[2] = myCars; Arrays are Objects Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays. But, JavaScript arrays are best described as arrays. Arrays use numbers to access its "elements". In this example, person[0] returns John: Array: var person = ["John", "Doe", 46]; Try it Yourself » Objects use names to access its "members". In this example, person.firstName returns John: Object: var person = {firstName:"John", lastName:"Doe", age:46}; Try it Yourself » Array Properties and Methods The real strength of JavaScript arrays are the built-in array properties and methods: Examples var x = cars.length; // The length property returns the number of elements in cars var y = cars.sort(); // The sort() method sort cars in alphabetical order Array methods are covered in the next chapter. The length Property The length property of an array returns the length of an array (the number of array elements). Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.length; // the length of fruits is 4 Try it Yourself » Note The length property is always one more than the highest array index. Adding Array Elements The easiest way to add a new element to an array is to use the length property: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits Try it Yourself » Adding elements with high indexes can create undefined "holes" in an array: Example var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[10] = "Lemon"; // adds a new element (Lemon) to fruits Try it Yourself » Looping Array Elements The best way to loop through an array is using a standard for loop: Example var index; var fruits = ["Banana", "Orange", "Apple", "Mango"]; for (index = 0; index < fruits.length; index++) { text += fruits[index]; } Try it Yourself » Associative Arrays? No Way! Many programming languages support arrays with named indexes. Arrays with named indexes are called associative arrays (or hashes). JavaScript does not support arrays with named indexes. Wrong: var person = new Array() person["firstName"] = "John"; person["lastName"] = "Doe"; person["age"] = 46; Try it Yourself » The example above looks like it works. But it does not. If you try it, person["firstName"] will return John, but person[0] will return undefined, and person.length will return 0. Note If you want to create an associative array, create an object instead. When to Use Arrays? When to use Objects? JavaScript does not support associative arrays. You should use objects when you want the element names to be strings. You should use arrays when you want the element names to be sequential numbers. Avoid new Array() There is no need to use the JavaScript's built-in array constructor new Array(). Use [] instead. These two different statements both create a new empty array named points: var points = new Array(); // Bad var points = []; // Good These two different statements both create a new array containing 6 numbers: var points = new Array(40, 100, 1, 5, 25, 10) // Bad var points = [40, 100, 1, 5, 25, 10]; // Good Try it Yourself » The new keyword complicates your code and produces nasty side effects: var points = new Array(40, 100); // Creates an array with two elements (40 and 100) What if I remove one of the elements? var points = new Array(40); // Creates an array with 40 undefined elements !!!!! Try it Yourself » How to Recognize an Array? A common question is: How do I know if a variable is an array? The problem is that the JavaScript operator typeof returns "object": var fruits = ["Banana", "Orange", "Apple", "Mango"]; typeof fruits; // typeof returns object Try it Yourself » The typeof operator returns object because a JavaScript array is an object. To solve this problem you can create your own isArray() function: function isArray(myArray) { return myArray.constructor.toString().indexOf("Array") > -1; } Try it Yourself » The function above always return true if the argument is an array. Or more precisely: it returns true if the object prototype of the argument is "[object array]".

How to create a margin in CSS

p { margin-top: 100px; margin-bottom: 100px; margin-right: 150px; margin-left: 50px; }

How do you make an element?

<body> <p>This is my first paragraph.</p> </body>

How do you make color text?

<!DOCTYPE html> <html> <head> <style> p { color: red; text-align: center; } </style> </head> <body> <p>Hello World!</p> <p>This paragraph is styled with CSS.</p> </body> </html>

How do you make headers?

<h1>This is a heading</h1> <h2>This is a heading</h2> <h3>This is a heading</h3>

How could you start CSS?

<!DOCTYPE html> <html> <body style="background-color:yellow;"> <h2 style="background-color:red;">This is a heading</h2> <p style="background-color:green;">This is a paragraph.</p> </body> </html> ==================================== <head> <style> body {background-color:yellow;} p {color:blue;} </style> </head> ==================================== <!DOCTYPE html> <html> <body> <h1 style="text-align:center;">Center-aligned heading</h1> <p>This is a paragraph.</p> </body> </html>

JavaScrip output

<!DOCTYPE html> <html> <body> <h1>My First Web Page</h1> <script> a = 5; b = 6; c = a + b; console.log(c); </script> </body> </html>

Script in <body>

<!DOCTYPE html> <html> <body> <h1>My Web Page</h1> <p id="demo">A Paragraph</p> <button type="button" onclick="myFunction()">Try it</button> <script> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } </script> </body> </html>

Script in <head>

<!DOCTYPE html> <html> <head> <script> function myFunction() { document.getElementById("demo").innerHTML = "Paragraph changed."; } </script> </head> <body> <h1>My Web Page</h1> <p id="demo">A Paragraph</p> <button type="button" onclick="myFunction()">Try it</button> </body> </html>

CSS combinators

<!DOCTYPE html> <html> <head> <style> div ~ p { background-color: yellow; } </style> </head> <body> <div> <p>Paragraph 1 in the div.</p> <p>Paragraph 2 in the div.</p> </div> <p>Paragraph 3. Not in a div.</p> <p>Paragraph 4. Not in a div.</p> </body> </html>

How do you format?

Tag Description <b> |Defines bold text <em> |Defines emphasized text <i> |Defines a part of text in an alternate voice or mood <small> | Defines smaller text <strong>| Defines important text <sub> |Defines subscripted text <sup> |Defines superscripted text <ins> |Defines inserted text <del> |Defines deleted text <mark> |Defines marked/highlighted text <abbr> |Defines an abbreviation or acronym <address>| Defines contact information for the author/owner of a document <bdo> |Defines the text direction <blockquote>| Defines a section that is quoted from another source <q> |Defines an inline (short) quotation <cite> |Defines the title of a work <dfn> |Defines a definition term

What are some attributes for blocks?

Tag Description <div> Defines a section in a document (block-level) <span> Defines a section in a document (inline)

What are some attributes of JavaScript

Tag Description <script> Defines a client-side script <noscript> Defines an alternate content for users that do not support client-side scripts

Variables

var x = 5; var y = 6; var z = x + y; ============================================ JavaScript Data Types JavaScript variables can hold many types of data, like text values (person = "John Doe"). In JavaScript texts are called strings or text strings. There are many types of JavaScript variables, but for now, just think of numbers and strings. When you assign a string value to a variable, you put double or single quotes around the value. When you assign a numeric value to a variable, you do not put quotes around the value. If you put quotes around a numeric value, it will be treated as a text string. Example var pi = 3.14; var person = "John Doe"; var answer = 'Yes I am!';

External Scripts

<!DOCTYPE html> <html> <body> <script src="myScript.js"></script> </body> </html>

JS JSON

JSON is a format for storing and transporting data. JSON is often used when data is sent from a server to a web page. What is JSON? JSON stands for JavaScript Object Notation JSON is lightweight data interchange format JSON is language independent * JSON is "self-describing" and easy to understand Note * JSON uses JavaScript syntax, but the JSON format is text only. Text can be read and used as a data format by any programming language. JSON Example This JSON syntax defines an employees object: an array of 3 employee records (objects): JSON Example {"employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ]} The JSON Format Evaluates to JavaScript Objects The JSON format is syntactically identical to the code for creating JavaScript objects. Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects. JSON Syntax Rules Data is in name/value pairs Data is separated by commas Curly braces hold objects Square brackets hold arrays JSON Data - A Name and a Value JSON data is written as name/value pairs, Just like JavaScript object properties. A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value: "firstName":"John" JSON Objects JSON objects are written inside curly braces. Just like in JavaScript, objects can contain multiple name/values pairs: {"firstName":"John", "lastName":"Doe"} JSON Arrays JSON arrays are written inside square brackets. Just like in JavaScript, an array can contain objects: "employees":[ {"firstName":"John", "lastName":"Doe"}, {"firstName":"Anna", "lastName":"Smith"}, {"firstName":"Peter", "lastName":"Jones"} ] In the example above, the object "employees" is an array. It contains three objects. Each object is a record of a person (with a first name and a last name). Converting a JSON Text to a JavaScript Object A common use of JSON is to read data from a web server, and display the data in a web page. For simplicity, this can be demonstrated using a string as input (or read more in our JSON tutorial): First, create a JavaScript string containing JSON syntax: var text = '{ "employees" : [' + '{ "firstName":"John" , "lastName":"Doe" },' + '{ "firstName":"Anna" , "lastName":"Smith" },' + '{ "firstName":"Peter" , "lastName":"Jones" } ]}'; Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object: var obj = JSON.parse(text); Finally, use the new JavaScript object in your page: Example <p id="demo"></p> <script> document.getElementById("demo").innerHTML = obj.employees[1].firstName + " " + obj.employees[1].lastName; </script> Try it yourself »

JavaScript

========================================================================================

JS Numbers

JavaScript Numbers « PreviousNext Chapter » JavaScript has only one type of number. Numbers can be written with, or without, decimals. JavaScript Numbers JavaScript numbers can be written with, or without decimals: Example var x = 3.14; // A number with decimals var y = 34; // A number without decimals Extra large or extra small numbers can be written with scientific (exponent) notation: Example var x = 123e5; // 12300000 var y = 123e-5; // 0.00123 JavaScript Numbers are Always 64-bit Floating Point Unlike many other programming languages, JavaScript does not define different types of numbers, like integers, short, long, floating-point etc. JavaScript numbers are always stored as double precision floating point numbers, following the international IEEE 754 standard. This format stores numbers in 64 bits, where the number (the fraction) is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63: Value (aka Fraction/Mantissa) Exponent Sign 52 bits (0 - 51) 11 bits (52 - 62) 1 bit (63) Precision Integers (numbers without a period or exponent notation) are considered accurate up to 15 digits. Example var x = 999999999999999; // x will be 999999999999999 var y = 9999999999999999; // y will be 10000000000000000 Try it yourself » The maximum number of decimals is 17, but floating point arithmetic is not always 100% accurate: Example var x = 0.2 + 0.1; // x will be 0.30000000000000004 Try it yourself » To solve the problem above, it helps to multiply and divide: Example var x = (0.2 * 10 + 0.1 * 10) / 10; // x will be 0.3 Try it yourself » Hexadecimal JavaScript interprets numeric constants as hexadecimal if they are preceded by 0x. Example var x = 0xFF; // x will be 255 Try it Yourself » Note Never write a number with a leading zero (like 07). Some JavaScript versions interpret numbers as octal if they are written with a leading zero. By default, Javascript displays numbers as base 10 decimals. But you can use the toString() method to output numbers as base 16 (hex), base 8 (octal), or base 2 (binary). Example var myNumber = 128; myNumber.toString(16); // returns 80 myNumber.toString(8); // returns 200 myNumber.toString(2); // returns 10000000 Try it Yourself » Infinity Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number. Example var myNumber = 2; while (myNumber != Infinity) { // Execute until Infinity myNumber = myNumber * myNumber; } Try it yourself » Division by 0 (zero) also generates Infinity: Example var x = 2 / 0; // x will be Infinity var y = -2 / 0; // y will be -Infinity Try it Yourself » Infinity is a number: typeOf Infinity returns number. Example typeof Infinity; // returns "number" Try it Yourself » NaN - Not a Number NaN is a JavaScript reserved word indicating that a value is not a number. You can use the global JavaScript function isNaN() to find out if a value is a number. Example var x = 100 / "Apple"; // a number divided by a string is not a number var y = 100 / "10"; // a number divided by a numeric string is a number Try it yourself » Infinity is a number. Example isNaN(1000 / 0); // returns false Try it Yourself » Watch out for NaN. If you use it in a mathematical operation, the result will also be NaN. Numbers Can be Objects Normally JavaScript numbers are primitive values created from literals: var x = 123 But numbers can also be defined as objects with the keyword new: var y = new Number(123) Example var x = 123; var y = new Number(123); typeof x; // returns number typeof y; // returns object Try it yourself » Note Don't create Number objects. They slow down execution speed, and produce nasty side effects: Example var x = 123; var y = new Number(123); (x === y) // is false because x is a number and y is an object. Try it yourself » Number Properties and Methods Primitive values (like 3.14 or 2014), cannot have properties and methods (because they are not objects). But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties. Number Properties Property Description MAX_VALUE Returns the largest number possible in JavaScript MIN_VALUE Returns the smallest number possible in JavaScript NEGATIVE_INFINITY Represents negative infinity (returned on overflow) NaN Represents a "Not-a-Number" value POSITIVE_INFINITY Represents infinity (returned on overflow) Example var x = Number.MAX_VALUE; Try it yourself » Number properties belongs to the JavaScript's number object wrapper called Number. These properties can only be accessed as Number.MAX_VALUE. Using myNumber.MAX_VALUE, where myNumber is a variable, expression, or value, will return undefined: Example var x = 6; var y = x.MAX_VALUE; // y becomes undefined Try it yourself »

JS Statement

document.getElementById("demo").innerHTML = "Hello Dolly."; document.getElementById("demo").innerHTML = "Hello Dolly."; document.getElementById("myDiv").innerHTML = "How are you?"; ============================================ Example function myFunction() { document.getElementById("demo").innerHTML = "Hello Dolly."; document.getElementById("myDIV").innerHTML = "How are you?"; } ============================================ Statement Description break Terminates a switch or a loop. catch Marks the block of statements to be executed when an error occurs in a try block. continue Jumps out of a loop and starts at the top. do ... while Executes a block of statements and repeats the block while a condition is true. for Marks a block of statements to be executed as long as a condition is true. for ... in Marks a block of statements to be executed for each element of an object (or array). function Declares a function. if ... else Marks a block of statements to be executed depending on a condition. return Exits a function. switch Marks a block of statements to be executed depending on different cases. throw Throws (generates) an error. try Implements error handling to a block of statements. var Declares a variable. while Marks a block of statements to be executed while a condition is true.

How to make an image opaque/ text inside an image

img { opacity: 0.4; filter: alpha(opacity=40); /* For IE8 and earlier */ } img:hover { opacity: 1.0; filter: alpha(opacity=100); /* For IE8 and earlier */ } ============================================ <html> <head> <style> div.background { width: 500px; height: 250px; background: url(klematis.jpg) repeat; border: 2px solid black; } div.transbox { width: 400px; height: 180px; margin: 30px 50px; background-color: #ffffff; border: 1px solid black; opacity: 0.6; filter: alpha(opacity=60); /* For IE8 and earlier */ } div.transbox p { margin: 30px 40px; font-weight: bold; color: #000000; } </style> </head> <body> <div class="background"> <div class="transbox"> <p>This is some text that is placed in the transparent box. This is some text that is placed in the transparent box. This is some text that is placed in the transparent box. This is some text that is placed in the transparent box. This is some text that is placed in the transparent box.</p> </div> </div> </body> </html>

How to create a color box around an image

<!DOCTYPE html> <html> <head> <style> a[target=_blank] { background-color: yellow; } </style> </head> <body> <p>The link with target="_blank" gets a yellow background:</p> <a href="http://www.w3schools.com">w3schools.com</a> <a href="http://www.disney.com" target="_blank">disney.com</a> <a href="http://www.wikipedia.org" target="_top">wikipedia.org</a> <p><b>Note:</b> For [<i>attribute</i>] to work in IE8 and earlier, a DOCTYPE must be declared.</p> </body> </html>

How do you make a better color text?

<!DOCTYPE html> <html> <head> <style> body { color: red; } h1 { color: #00ff00; } p.ex { color: rgb(0,0,255); } </style> </head> <body> <h1>This is heading 1</h1> <p>This is an ordinary paragraph. Notice that this text is red. The default text-color for a page is defined in the body selector.</p> <p class="ex">This is a paragraph with class="ex". This text is blue.</p> </body> </html> ============================================ body { color: blue; } h1 { color: #00ff00; } h2 { color: rgb(255,0,0); }

How to align

<!DOCTYPE html> <html> <head> <style> body { margin: 0; padding: 0; } .container { position: relative; width: 100%; } .right { position: absolute; right: 0px; width: 300px; background-color: #b0e0e6; } </style> </head> <body> <div class="container"> <div class="right"> <p><b>Note: </b>When aligning using the position property, always include the !DOCTYPE declaration! If missing, it can produce strange results in IE browsers.</p> </div> </div> </body> </html>

How do you make a centered colored Document?

<!DOCTYPE html> <html> <head> <style> h1, h2, p { text-align: center; color: red; } </style> </head> <body> <h1>Hello World!</h1> <h2>Smaller heading!</h2> <p>This is a paragraph.</p> </body> </html>

How to create an img positioning

<!DOCTYPE html> <html> <head> <style> img { position: absolute; left: 0px; top: 0px; z-index: -1; } </style> </head> <body> <h1>This is a heading</h1> <img src="w3css.gif" width="100" height="140"> <p>Because the image has a z-index of -1, it will be placed behind the text.</p> </body> </html>

Image Sprites

<!DOCTYPE html> <html> <head> <style> img.home { width: 46px; height: 44px; background: url(img_navsprites.gif) 0 0; } img.next { width: 43px; height: 44px; background: url(img_navsprites.gif) -91px 0; } </style> </head> <body> <img class="home" src="img_trans.gif"><br><br> <img class="next" src="img_trans.gif"> </body> </html>

How do you make a link?

<a href="default.htm"> This is a link </a>

How do you create links?

<a href="http://www.w3schools.com/" target="_blank">Visit W3Schools!</a>

How do you add JavaScript to an HTML document?

<script> document.getElementById("demo").innerHTML = "Hello JavaScript!"; </script> <noscript>Sorry, your browser does not support JavaScript!</noscript>

How do you make tables?

<table style="width:300px"> <tr> <th>Firstname</th> <th>Lastname</th> <th>Points</th> </tr> <tr> <td>Eve</td> <td>Jackson</td> <td>94</td> </tr> </table>

How to create a navigation bar

<ul> <li><a href="default.asp">Home</a></li> <li><a href="news.asp">News</a></li> <li><a href="contact.asp">Contact</a></li> <li><a href="about.asp">About</a></li> </ul>

How do you create lists?

<ul> <li>Coffee</li> <li>Milk</li> </ul> How the HTML code above looks in a browser: Coffee Milk ==================================== <dl> <dt>Coffee</dt> <dd>- black hot drink</dd> <dt>Milk</dt> <dd>- white cold drink</dd> </dl> How the HTML code above looks in a browser: Coffee - black hot drink Milk - white cold drink

CSS

================================================================================================

How do you make a check box?

Checkboxes <input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE options of a limited number of choices. <form> <input type="checkbox" name="vehicle" value="Bike">I have a bike<br> <input type="checkbox" name="vehicle" value="Car">I have a car </form> How the HTML code above looks in a browser: I have a bike I have a car

What are some color names?

AliceBlue #F0F8FF Shades Mix AntiqueWhite #FAEBD7 Shades Mix Aqua #00FFFF Shades Mix Aquamarine #7FFFD4 Shades Mix Azure #F0FFFF Shades Mix Beige #F5F5DC Shades Mix Bisque #FFE4C4 Shades Mix Black #000000 Shades Mix BlanchedAlmond #FFEBCD Shades Mix Blue #0000FF Shades Mix BlueViolet #8A2BE2 Shades Mix Brown #A52A2A Shades Mix BurlyWood #DEB887 Shades Mix CadetBlue #5F9EA0 Shades Mix Chartreuse #7FFF00 Shades Mix Chocolate #D2691E Shades Mix Coral #FF7F50 Shades Mix CornflowerBlue #6495ED Shades Mix Cornsilk #FFF8DC Shades Mix Crimson #DC143C Shades Mix Cyan #00FFFF Shades Mix DarkBlue #00008B Shades Mix DarkCyan #008B8B Shades Mix DarkGoldenRod #B8860B Shades Mix DarkGray #A9A9A9 Shades Mix DarkGreen #006400 Shades Mix DarkKhaki #BDB76B Shades Mix DarkMagenta #8B008B Shades Mix DarkOliveGreen #556B2F Shades Mix DarkOrange #FF8C00 Shades Mix DarkOrchid #9932CC Shades Mix DarkRed #8B0000 Shades Mix DarkSalmon #E9967A Shades Mix DarkSeaGreen #8FBC8F Shades Mix DarkSlateBlue #483D8B Shades Mix DarkSlateGray #2F4F4F Shades Mix DarkTurquoise #00CED1 Shades Mix DarkViolet #9400D3 Shades Mix DeepPink #FF1493 Shades Mix DeepSkyBlue #00BFFF Shades Mix DimGray #696969 Shades Mix DodgerBlue #1E90FF Shades Mix FireBrick #B22222 Shades Mix FloralWhite #FFFAF0 Shades Mix ForestGreen #228B22 Shades Mix Fuchsia #FF00FF Shades Mix Gainsboro #DCDCDC Shades Mix GhostWhite #F8F8FF Shades Mix Gold #FFD700 Shades Mix GoldenRod #DAA520 Shades Mix Gray #808080 Shades Mix Green #008000 Shades Mix GreenYellow #ADFF2F Shades Mix HoneyDew #F0FFF0 Shades Mix HotPink #FF69B4 Shades Mix IndianRed #CD5C5C Shades Mix Indigo #4B0082 Shades Mix Ivory #FFFFF0 Shades Mix Khaki #F0E68C Shades Mix Lavender #E6E6FA Shades Mix LavenderBlush #FFF0F5 Shades Mix LawnGreen #7CFC00 Shades Mix LemonChiffon #FFFACD Shades Mix LightBlue #ADD8E6 Shades Mix LightCoral #F08080 Shades Mix LightCyan #E0FFFF Shades Mix LightGoldenRodYellow #FAFAD2 Shades Mix LightGray #D3D3D3 Shades Mix LightGreen #90EE90 Shades Mix LightPink #FFB6C1 Shades Mix LightSalmon #FFA07A Shades Mix LightSeaGreen #20B2AA Shades Mix LightSkyBlue #87CEFA Shades Mix LightSlateGray #778899 Shades Mix LightSteelBlue #B0C4DE Shades Mix LightYellow #FFFFE0 Shades Mix Lime #00FF00 Shades Mix LimeGreen #32CD32 Shades Mix Linen #FAF0E6 Shades Mix Magenta #FF00FF Shades Mix Maroon #800000 Shades Mix MediumAquaMarine #66CDAA Shades Mix MediumBlue #0000CD Shades Mix MediumOrchid #BA55D3 Shades Mix MediumPurple #9370DB Shades Mix MediumSeaGreen #3CB371 Shades Mix MediumSlateBlue #7B68EE Shades Mix MediumSpringGreen #00FA9A Shades Mix MediumTurquoise #48D1CC Shades Mix MediumVioletRed #C71585 Shades Mix MidnightBlue #191970 Shades Mix MintCream #F5FFFA Shades Mix MistyRose #FFE4E1 Shades Mix Moccasin #FFE4B5 Shades Mix NavajoWhite #FFDEAD Shades Mix Navy #000080 Shades Mix OldLace #FDF5E6 Shades Mix Olive #808000 Shades Mix OliveDrab #6B8E23 Shades Mix Orange #FFA500 Shades Mix OrangeRed #FF4500 Shades Mix Orchid #DA70D6 Shades Mix PaleGoldenRod #EEE8AA Shades Mix PaleGreen #98FB98 Shades Mix PaleTurquoise #AFEEEE Shades Mix PaleVioletRed #DB7093 Shades Mix PapayaWhip #FFEFD5 Shades Mix PeachPuff #FFDAB9 Shades Mix Peru #CD853F Shades Mix Pink #FFC0CB Shades Mix Plum #DDA0DD Shades Mix PowderBlue #B0E0E6 Shades Mix Purple #800080 Shades Mix Red #FF0000 Shades Mix RosyBrown #BC8F8F Shades Mix RoyalBlue #4169E1 Shades Mix SaddleBrown #8B4513 Shades Mix Salmon #FA8072 Shades Mix SandyBrown #F4A460 Shades Mix SeaGreen #2E8B57 Shades Mix SeaShell #FFF5EE Shades Mix Sienna #A0522D Shades Mix Silver #C0C0C0 Shades Mix SkyBlue #87CEEB Shades Mix SlateBlue #6A5ACD Shades Mix SlateGray #708090 Shades Mix Snow #FFFAFA Shades Mix SpringGreen #00FF7F Shades Mix SteelBlue #4682B4 Shades Mix Tan #D2B48C Shades Mix Teal #008080 Shades Mix Thistle #D8BFD8 Shades Mix Tomato #FF6347 Shades Mix Turquoise #40E0D0 Shades Mix Violet #EE82EE Shades Mix Wheat #F5DEB3 Shades Mix White #FFFFFF Shades Mix WhiteSmoke #F5F5F5 Shades Mix Yellow #FFFF00 Shades Mix YellowGreen #9ACD32 Shades Mix

JS Comparisons

JavaScript Comparison and Logical Operators « PreviousNext Chapter » Comparison and Logical operators are used to test for true or false. Comparison Operators Comparison operators are used in logical statements to determine equality or difference between variables or values. Given that x=5, the table below explains the comparison operators: Operator Description Comparing Returns Try it == equal to x == 8 false Try it » x == 5 true Try it » === equal value and equal type x === "5" false Try it » x === 5 true Try it » != not equal x != 8 true Try it » !== not equal value or not equal type x !== "5" true Try it » x !== 5 false Try it » > greater than x > 8 false Try it » < less than x < 8 true Try it » >= greater than or equal to x >= 8 false Try it » <= less than or equal to x <= 8 true Try it » How Can it be Used Comparison operators can be used in conditional statements to compare values and take action depending on the result: if (age < 18) text = "Too young"; You will learn more about the use of conditional statements in the next chapter of this tutorial. Logical Operators Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators: Operator Description Example && and (x < 10 && y > 1) is true || or (x == 5 || y == 5) is false ! not !(x == y) is true Conditional Operator JavaScript also contains a conditional operator that assigns a value to a variable based on some condition. Syntax variablename = (condition) ? value1:value2 Example voteable = (age < 18) ? "Too young":"Old enough"; Try it Yourself »

JS Reserved Words

JavaScript Reserved Words « PreviousNext Chapter » In JavaScript, some identifiers are reserved words and cannot be used as variables or function names. JavaScript Standards All modern browsers fully support ECMAScript 3 (ES3, the third edition of JavaScript from 1999). ECMAScript 4 (ES4) was never adopted. ECMAScript 5 (ES5, released in 2009) is the latest official version of JavaScript. Time passes, and we are now beginning to see complete support for ES5 in all modern browsers. JavaScript Reserved Words In JavaScript you cannot use these reserved words as variables, labels, or function names: abstract arguments boolean break byte case catch char class* const continue debugger default delete do double else enum* eval export* extends* false final finally float for function goto if implements import* in instanceof int interface let long native new null package private protected public return short static super* switch synchronized this throw throws transient true try typeof var void volatile while with yield Words marked with* are new in ECMAScript5 JavaScript Objects, Properties, and Methods You should also avoid using the name of JavaScript built-in objects, properties, and methods: Array Date eval function hasOwnProperty Infinity isFinite isNaN isPrototypeOf length Math NaN name Number Object prototype String toString undefined valueOf Java Reserved Words JavaScript is often used together with Java. You should avoid using some Java objects and properties as JavaScript identifiers: getClass java JavaArray javaClass JavaObject JavaPackage Windows Reserved Words JavaScript can be used outside HTML. It can be used as the programming language in many other applications. In HTML you must (for portability you should) avoid using the name of HTML and Windows objects and properties: alert all anchor anchors area assign blur button checkbox clearInterval clearTimeout clientInformation close closed confirm constructor crypto decodeURI decodeURIComponent defaultStatus document element elements embed embeds encodeURI encodeURIComponent escape event fileUpload focus form forms frame innerHeight innerWidth layer layers link location mimeTypes navigate navigator frames frameRate hidden history image images offscreenBuffering open opener option outerHeight outerWidth packages pageXOffset pageYOffset parent parseFloat parseInt password pkcs11 plugin prompt propertyIsEnum radio reset screenX screenY scroll secure select self setInterval setTimeout status submit taint text textarea top unescape untaint window HTML Event Handlers In addition you should avoid using the name of all HTML event handlers. Examples: onblur onclick onerror onfocus onkeydown onkeypress onkeyup onmouseover onload onmouseup onmousedown onsubmit Nonstandard JavaScript In addition to reserved words, there are also some nonstandard keywords used in some JavaScript implementations. One example is the const keyword used to define variables. Some JavaScript engines will treat const as a synonym to var. Other engines will treat const as a definition for read-only variables. Const is an extension to JavaScript. It is supported by the JavaScript engine used in Firefox and Chrome. But it is not a part of the JavaScript standards ES3 or ES5. Do not use it.

String methods

JavaScript String Methods « PreviousNext Chapter » String methods help you to work with strings. Finding a String in a String The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string: Example var str = "Please locate where 'locate' occurs!"; var pos = str.indexOf("locate"); Try it Yourself » The lastIndexOf() method returns the index of the last occurrence of a specified text in a string: Example var str = "Please locate where 'locate' occurs!"; var pos = str.lastIndexOf("locate"); Try it Yourself » Both the indexOf(), and the lastIndexOf() methods return -1 if the text is not found. Note JavaScript counts positions from zero. 0 is the first position in a string, 1 is the second, 2 is the third ... Both methods accept a second parameter as the starting position for the search. Searching for a String in a String The search() method searches a string for a specified value and returns the position of the match: Example var str = "Please locate where 'locate' occurs!"; var pos = str.search("locate"); Try it Yourself » Note Did You Notice? The two methods, indexOf() and search(), are equal. They accept the same arguments (parameters), and they return the same value. The two methods are equal, but the search() method can take much more powerful search values. You will learn more about powerful search values in the chapter about regular expressions. Extracting String Parts There are 3 methods for extracting a part of a string: slice(start, end) substring(start, end) substr(start, length) The slice() Method slice() extracts a part of a string and returns the extracted part in a new string. The method takes 2 parameters: the starting index (position), and the ending index (position). This example slices out a portion of a string from position 7 to position 13: Example var str = "Apple, Banana, Kiwi"; var res = str.slice(7,13); The result of res will be: Banana Try it yourself » If a parameter is negative, the position is counted from the end of the string. This example slices out a portion of a string from position -12 to position -6: Example var str = "Apple, Banana, Kiwi"; var res = str.slice(-12,-6); The result of res will be: Banana Try it yourself » If you omit the second parameter, the method will slice out the rest of the sting: Example var res = str.slice(7); Try it yourself » or, counting from the end: Example var res = str.slice(-12); Try it yourself » Note Negative positions does not work in Internet Explorer 8 and earlier. The substring() Method substring() is similar to slice(). The difference is that substring() cannot accept negative indexes. Example var str = "Apple, Banana, Kiwi"; var res = str.substring(7,13); The result of res will be: Banana Try it yourself » If you omit the second parameter, substring() will slice out the rest of the string. The substr() Method substr() is similar to slice(). The difference is that the second parameter specifies the length of the extracted part. Example var str = "Apple, Banana, Kiwi"; var res = str.substr(7,6); The result of res will be: Banana Try it yourself » If the first parameter is negative, the position counts from the end of the string. The second parameter can not be negative, because it defines the length. If you omit the second parameter, substr() will slice out the rest of the string. Replacing String Content The replace() method replaces a specified value with another value in a string: Example str = "Please visit Microsoft!"; var n = str.replace("Microsoft","W3Schools"); Try it Yourself » The replace() method can also take a regular expression as the search value. Converting to Upper and Lower Case A string is converted to upper case with toUpperCase(): Example var text1 = "Hello World!"; // String var text2 = text1.toUpperCase(); // text2 is text1 converted to upper Try it Yourself » A string is converted to lower case with toLowerCase(): Example var text1 = "Hello World!"; // String var text2 = text1.toLowerCase(); // text2 is text1 converted to lower var ola Try it Yourself » The concat() Method concat() joins two or more strings: Example var text1 = "Hello"; var text2 = "World"; text3 = text1.concat(" ",text2); Try it Yourself » The concat() method can be used instead of the plus operator. These two lines do the same: Example var text = "Hello" + " " + "World!"; var text = "Hello".concat(" ","World!"); Note All string methods return a new string. They don't modify the original string. Formally said: Strings are immutable: Strings cannot be changed, only replaced. Extracting String Characters There are 2 safe methods for extracting string characters: charAt(position) charCodeAt(position) The charAt() Method The charAt() method returns the character at a specified index (position) in a string: Example var str = "HELLO WORLD"; str.charAt(0); // returns H Try it Yourself » The charCodeAt() Method The charCodeAt() method returns the unicode of the character at a specified index in a string: Example var str = "HELLO WORLD"; str.charCodeAt(0); // returns 72 Try it Yourself » Accessing a String as an Array is Unsafe You might have seen code like this, accessing a string as an array: var str = "HELLO WORLD"; str[0]; // returns H This is unsafe and unpredictable: It does not work in all browsers (not in IE5, IE6, IE7) It makes strings look like arrays (but they are not) str[0] = "H" does not give an error (but does not work) If you want to read a string as an array, convert it to an array first. Converting a String to an Array A string can be converted to an array with the split() method: Example var txt = "a,b,c,d,e"; // String txt.split(","); // Split on commas txt.split(" "); // Split on spaces txt.split("|"); // Split on pipe Try it Yourself » If the separator is omitted, the returned array will contain the whole string in index [0]. If the separator is "", the returned array will be an array of single characters: Example var txt = "Hello"; // String txt.split(""); // Split in characters Try it Yourself » Complete String Reference For a complete reference, go to our Complete JavaScript String Reference. The reference contains descriptions and examples of all string properties and methods.

What would a layout look like?

Website Layouts Most websites have put their content in multiple columns (formatted like a magazine or newspaper). Multiple columns are created by using <div> or <table> elements. CSS are used to position elements, or to create backgrounds or colorful look for the pages. Note Even though it is possible to create nice layouts with HTML tables, tables were designed for presenting tabular data - NOT as a layout tool! HTML Layouts - Using <div> Elements The div element is a block level element used for grouping HTML elements. The following example uses five div elements to create a multiple column layout, creating the same result as in the previous example: Example <!DOCTYPE html> <html> <body> <div id="container" style="width:500px"> <div id="header" style="background-color:#FFA500;"> <h1 style="margin-bottom:0;">Main Title of Web Page</h1></div> <div id="menu" style="background-color:#FFD700;height:200px;width:100px;float:left;"> <b>Menu</b><br> HTML<br> CSS<br> JavaScript</div> <div id="content" style="background-color:#EEEEEE;height:200px;width:400px;float:left;"> Content goes here</div> <div id="footer" style="background-color:#FFA500;clear:both;text-align:center;"> Copyright © W3Schools.com</div> </div> </body> </html> Try it yourself » The HTML code above will produce the following result: Main Title of Web Page Menu HTML CSS JavaScript Content goes here Copyright © W3Schools.com HTML Layouts - Using Tables A simple way of creating layouts is by using the HTML <table> tag. Multiple columns are created by using <div> or <table> elements. CSS are used to position elements, or to create backgrounds or colorful look for the pages. Note Using <table> to create a nice layout is NOT the correct use of the element. The purpose of the <table> element is to display tabular data! The following example uses a table with 3 rows and 2 columns - the first and last row spans both columns using the colspan attribute: Example <!DOCTYPE html> <html> <body> <table style="width:500px;" cellpadding="0" cellspacing="0"> <tr> <td colspan="2" style="background-color:#FFA500;"> <h1 style="margin:0;padding:0;">Main Title of Web Page</h1> </td> </tr> <tr> <td style="background-color:#FFD700;width:100px;vertical-align:top;"> <b>Menu</b><br> HTML<br> CSS<br> JavaScript </td> <td style="background-color:#eeeeee;height:200px;width:400px;vertical-align:top;"> Content goes here</td> </tr> <tr> <td colspan="2" style="background-color:#FFA500;text-align:center;"> Copyright © W3Schools.com</td> </tr> </table> </body> </html> Try it yourself » HTML Layout - Useful Tips Tip: The biggest advantage of using CSS is that, if you place the CSS code in an external style sheet, your site becomes MUCH EASIER to maintain. You can change the layout of all your pages by editing one file. To learn more about CSS, study our CSS tutorial. Tip: Because advanced layouts take time to create, a quicker option is to use a template. Search Google for free website templates (these are pre-built website layouts you can use and customize). HTML Layout Tags Tag Description <div> Defines a section in a document (block-level) <span> Defines a section in a document (inline)

How to make a media type

<!DOCTYPE html> <html> <head> <style> @media screen { p { font-family: verdana,sans-serif; font-size: 14px; } } @media print { p { font-size: 20px; color: red; } } </style> </head> <body> <h2>The @media Rule</h2> <p>The @media rule allows different style rules for different media in the same style sheet.</p> <p>The style in this example tells the browser to display a 14 pixels Verdana font on the screen. However, if the page is printed, the text will be in 20 pixels Verdana font, and in a red color.</p> <p><b>See it yourself !</b> Print this page (or open Print Preview), and you will see that the text will be displayed in a larger font size, and in red color.</p> </body> </html>

How do you make an image in HTML?

<img src="w3schools.jpg" alt="W3Schools.com" width="104" height="142">

What are some attributes for lists?

<ol> Defines an ordered list <ul> Defines an unordered list <li> Defines a list item <dl> Defines a description list <dt> Defines a term/name in a description list <dd> Defines a description of a term/name in a description list

How do you make paragraphs?

<p>This is a paragraph</p> <p>This is another paragraph</p>

How to create a Pseudo-class

/* unvisited link */ a:link { color: #FF0000; } /* visited link */ a:visited { color: #00FF00; } /* mouse over link */ a:hover { color: #FF00FF; } /* selected link */ a:active { color: #0000FF; }

How to create a link in CSS

a:link { background-color: #B2FF99; } a:visited { background-color: #FFFF85; } a:hover { background-color: #FF704D; } a:active { background-color: #FF704D; }

How do you add color backgrounds?

body { background-image: url("gradient.png"); background-repeat: repeat-x; }

How to create a Pseudo-element

p::first-line { color: #ff0000; font-variant: small-caps; }

How to make an image galary

<html> <head> <style> div.img { margin: 5px; padding: 5px; border: 1px solid #0000ff; height: auto; width: auto; float: left; text-align: center; } div.img img { display: inline; margin: 5px; border: 1px solid #ffffff; } div.img a:hover img { border:1px solid #0000ff; } div.desc { text-align: center; font-weight: normal; width: 120px; margin: 5px; } </style> </head> <body> <div class="img"> <a target="_blank" href="klematis_big.htm"> <img src="klematis_small.jpg" alt="Klematis" width="110" height="90"> </a> <div class="desc">Add a description of the image here</div> </div> <div class="img"> <a target="_blank" href="klematis2_big.htm"> <img src="klematis2_small.jpg" alt="Klematis" width="110" height="90"> </a> <div class="desc">Add a description of the image here</div> </div> <div class="img"> <a target="_blank" href="klematis3_big.htm"> <img src="klematis3_small.jpg" alt="Klematis" width="110" height="90"> </a> <div class="desc">Add a description of the image here</div> </div> <div class="img"> <a target="_blank" href="klematis4_big.htm"> <img src="klematis4_small.jpg" alt="Klematis" width="110" height="90"> </a> <div class="desc">Add a description of the image here</div> </div> </body> </html>

How do you make an iframe?

<iframe src="demo_iframe.htm" width="200" height="200"></iframe>

How do you create images?

<img src="url" alt="some_text">

Scope, Local/Global variables

Example // code here can not use carName function myFunction() { var carName = "Volvo"; // code here can use carName } Try it Yourself » Since local variables are only recognized inside their functions, variables with the same name can be used in different functions. Local variables are created when a function starts, and deleted when the function is completed. Global JavaScript Variables A variable declared outside a function, becomes GLOBAL. A global variable has global scope: All scripts and functions on a web page can access it. Example var carName = " Volvo"; // code here can use carName function myFunction() { // code here can use carName } Try it Yourself » Automatically Global If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. This code example will declare carName as a global variable, even if it is executed inside a function. Example // code here can use carName function myFunction() { carName = "Volvo"; // code here can use carName } Try it Yourself » The Lifetime of JavaScript Variables The lifetime of a JavaScript variable starts when it is declared. Local variables are deleted when the function is completed. Global variables are deleted when you close the page. Function Arguments Function arguments (parameters) work as local variables inside functions. Global Variables in HTML With JavaScript, the global scope is the complete JavaScript environment. In HTML, the global scope is the window object: All global variables belong to the window object. Example // code here can use window.carName function myFunction() { carName = "Volvo"; }

JS Syntax

Expression literals evaluates (computes) to a value: 5 + 6 5 * 10 =========================== String literals can be written with double or single quotes: "John Doe" 'John Doe' =========================== Array literals defines an array: [40, 100, 1, 5, 25, 10] Object literals defines an object: {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"} Function literals defines a function: function myFunction(a, b) { return a * b;} ============================ JavaScript uses an assignment operator to assign values to variables (just like algebra): x = 5 y = 6 z = (x + y) * 10 ============================ Type Examples Description Assignment, arithmetic, and bitwise operators = + - * / Described in JS Operators Conditional, comparison, and logical operators == != < > Described in JS Comparisons

JS in html Events

HTML Events An HTML event can be something the browser does, or something a user does. Here are some examples of HTML events: An HTML web page has finished loading An HTML input field was changed An HTML button was clicked Often, when events happen, you may want to do something. JavaScript lets you execute code when events are detected. HTML allows event handler attributes, with JavaScript code, to be added to HTML elements. With single quotes: <some-HTML-element some-event='some JavaScript'> With double quotes: <some-HTML-element some-event="some JavaScript"> In the following example, an onclick attribute (with code), is added to a button element: Example <button onclick='getElementById("demo").innerHTML=Date()'>The time is?</button> Try it Yourself » In the example above, the JavaScript code changes the content of the element with id="demo". In the next example, the code changes the content of it's own element (using this.innerHTML): Example <button onclick="this.innerHTML=Date()">The time is?</button> Try it Yourself » Note JavaScript code is often several lines long. It is more common to see event attributes calling functions: Example <button onclick="displayDate()">The time is?</button> Try it Yourself » Common HTML Events Here is a list of some common HTML events: Event Description onchange An HTML element has been changed onclick The user clicks an HTML element onmouseover The user moves the mouse over an HTML element onmouseout The user moves the mouse away from an HTML element onkeydown The user pushes a keyboard key onload The browser has finished loading the page The list is much longer: W3Schools JavaScript Reference HTML DOM Events. What can JavaScript Do? Event handlers can be used to handle, and verify, user input, user actions, and browser actions: Things that should be done every time a page loads Things that should be done when the page is closed Action that should be performed when a user clicks a button Content that should be verified when a user input data And more ... Many different methods can be used to let JavaScript work with events: HTML event attributes can execute JavaScript code directly HTML event attributes can call JavaScript functions You can assign your own event handler functions to HTML elements You can prevent events from being sent or being handled And more ...

JS best Practices

JavaScript Best Practices « PreviousNext Chapter » Avoid global variables, avoid new, avoid ==, avoid eval() Avoid Global Variables Avoid using global variables. This includes all data types, objects, and functions. Global variables and functions can be overwritten by other scripts. Use local variables instead, and learn how to use closures. Always Declare Local Variables All variables used in a function should be declared as local variables. Local variables must be declared with the var keyword, otherwise they will become global variables. Note Strict mode does not allow undeclared variables. Never Declare Numbers, Strings, or Booleans as Objects Always treat numbers, strings, or booleans as primitive values. Not as objects. Declaring numbers, strings, or booleans as objects, slows down execution speed, and produces nasty side effects: Example var x = "John"; var y = new String("John"); (x === y) // is false because x is a string and y is an object. Try it yourself » Don't Use new Object() Use {} instead of new Object() Use "" instead of new String() Use 0 instead of new Number() Use false instead of new Boolean() Use [] instead of new Array() Use /(:)/ instead of new RegExp() Use function (){} instead of new function() Example var x1 = {}; // new object var x2 = ""; // new primitive string var x3 = 0; // new primitive number var x4 = false; // new primitive boolean var x5 = []; // new array object var x6 = /()/ // new regexp object var x7 = function(){}; // new function object Try it Yourself » Beware of Automatic Type Conversions Beware that numbers can accidentally be converted to strings or NaN (Not a Number). JavaScript is loosely typed. A variable can contain different data types, and a variable can change its data type: Example var x = "Hello"; // typeof x is a string x = 5; // changes typeof x to a number Try it yourself » When doing mathematical operations, JavaScript can convert numbers to strings: Example var x = 5 + 7; // x.valueOf() is 12, typeof x is a number var x = 5 + "7"; // x.valueOf() is 57, typeof x is a string var x = "5" + 7; // x.valueOf() is 57, typeof x is a string var x = 5 - 7; // x.valueOf() is -2, typeof x is a number var x = 5 - "7"; // x.valueOf() is -2, typeof x is a number var x = "5" - 7; // x.valueOf() is -2, typeof x is a number var x = 5 - "x"; // x.valueOf() is NaN, typeof x is a number Try it yourself » Subtracting a string from a string, does not generate an error but returns NaN (Not a Number): Example "Hello" - "Dolly" // returns NaN Try it yourself » Use === Comparison The == comparison operator always converts (to matching types) before comparison. The === operator forces comparison of values and type: Example 0 == ""; // true 1 == "1"; // true 1 == true; // true 0 === ""; // false 1 === "1"; // false 1 === true; // false Try it yourself » Never End a Definition with a Comma Bad Examples points = [40, 100, 1, 5, 25, 10, ]; person = {firstName:"John", lastName:"Doe", age:46, } Some JSON and JavaScript engines will fail, or behave unexpectedly. Use Parameter Defaults If a function is called with a missing argument, the value of the missing argument is set to undefined. Undefined values can break your code. It is a good habit to assign default values to arguments. Example function myFunction(x, y) { if (y === undefined) { y = 0; } } Or, even simpler: function myFunction(x, y) { y = y || 0; } Try it Yourself »

JS Booleans

JavaScript Booleans « PreviousNext Chapter » A JavaScript Boolean represents one of two values: true or false. The Boolean() Function You can use the Boolean() function to find out if an expression (or a variable) is true: Example Boolean(10 > 9) // returns true Try it Yourself » Or even easier: Example (10 > 9) // also returns true 10 > 9 // also returns true Try it Yourself » Note The Boolean value of an expression is the fundament for JavaScript comparisons and conditions. Everything With a Real Value is True Examples 100 3.14 -15 "Hello" "false" 7 + 1 + 3.14 5 < 6 Try it Yourself » Everything Without a Real Value is False The Boolean value of 0 (zero) is false: var x = 0; Boolean(x); // returns false Try it Yourself » The Boolean value of -0 (minus zero) is false: var x = -0; Boolean(x); // returns false Try it Yourself » The Boolean value of "" (empty string) is false: var x = ""; Boolean(x); // returns false Try it Yourself » The Boolean value of undefined is false: var x; Boolean(x); // returns false Try it Yourself » The Boolean value of null is false: var x = null; Boolean(x); // returns false Try it Yourself » The Boolean value of false is (you guessed it) false: var x = false; Boolean(x); // returns false Try it Yourself » The Boolean value of NaN is false: var x = 10 / "H"; Boolean(x); // returns false Try it Yourself » Boolean Properties and Methods Primitive values, like true and false, cannot have properties or methods (because they are not objects). But with JavaScript, methods and properties are also available to primitive values, because JavaScript treats primitive values as objects when executing methods and properties.

JS breaks

JavaScript Break and Continue « PreviousNext Chapter » The break statement "jumps out" of a loop. The continue statement "jumps over" one iteration in the loop. The Break Statement You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch() statement. The break statement can also be used to jump out of a loop. The break statement breaks the loop and continues executing the code after the loop (if any): Example for (i = 0; i < 10; i++) { if (i == 3) { break } text += "The number is " + i + "<br>"; } Try it Yourself » Since the if statement has only one single line of code, the braces can be omitted: for (i = 0; i < 10; i++) { if (i == 3) break; text += "The number is " + i + "<br>"; } The Continue Statement The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop. This example skips the value of 3: Example for (i = 0; i <= 10; i++) { if (i == 3) continue; text += "The number is " + i + "<br>"; } Try it Yourself » JavaScript Labels As you have already seen, in the chapter about the switch statement, JavaScript statements can be labeled. To label JavaScript statements you precede the statements with a label name and a colon: label: statements The break and the continue statements are the only JavaScript statements that can "jump out of" a code block. Syntax: break labelname; continue labelname; The continue statement (with or without a label reference) can only be used inside a loop. The break statement, without a label reference, can only be used inside a loop or a switch. With a label reference, it can be used to "jump out of" any JavaScript code block: Example cars = ["BMW", "Volvo", "Saab", "Ford"]; list: { text += cars[0] + "<br>"; text += cars[1] + "<br>"; text += cars[2] + "<br>"; text += cars[3] + "<br>"; break list; text += cars[4] + "<br>"; text += cars[5] + "<br>"; } Try it Yourself »

JS Date methods

JavaScript Date Methods « PreviousNext Chapter » Date methods let you get and set date values (years, months, days, minutes, seconds, milliseconds) Date Get Methods Get methods are used for getting a part of a date. Here are the most common (alphabetically): Method Description getDate() Get the day as a number (1-31) getDay() Get the weekday a number (0-6) getFullYear() Get the four digit year (yyyy) getHours() Get the hour (0-23) getMilliseconds() Get the milliseconds (0-999) getMinutes() Get the minutes (0-59) getMonth() Get the month (0-11) getSeconds() Get the seconds (0-59) getTime() Get the time (milliseconds since January 1, 1970) The getTime() Method getTime() returns the the number of milliseconds since 01.01.1970: Example <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getTime(); </script> Try it Yourself » The getFullYear() Method getFullYear() returns the year of a date as a four digit number: Example <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getFullYear(); </script> Try it Yourself » The getDay() Method getDay() returns the weekday as a number (0-6): Example <script> var d = new Date(); document.getElementById("demo").innerHTML = d.getDay(); </script> Try it Yourself » You can use an array of names, and getDay() to return the weekday as a name: Example <script> var d = new Date(); var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]; document.getElementById("demo").innerHTML = days[d.getDay()]; </script> Try it Yourself » Date Set Methods Set methods are used for setting a part of a date. Here are the most common (alphabitically): Method Description setDate() Set the day as a number (1-31) setFullYear() Set the year (optionally month and day yyyy.mm.dd) setHours() Set the hour (0-23) setMilliseconds() Set the milliseconds (0-999) setMinutes() Set the minutes (0-59) setMonth() Set the month (0-11) setSeconds() Set the seconds (0-59) setTime() Set the time (milliseconds since January 1, 1970) The setFullYear() Method setFullYear() sets a date object to a specific date. In this example, to January 14, 2020: Example <script> var d = new Date(); d.setFullYear(2020, 0, 14); document.getElementById("demo").innerHTML = d; </script> Try it Yourself » The setDate() Method setDate() sets the day of the month (1-31): Example <script> var d = new Date(); d.setDate(20); document.getElementById("demo").innerHTML = d; </script> Try it Yourself » The setDate() method can also be used to add days to a date: Example <script> var d = new Date(); d.setDate(d.getDate() + 50); document.getElementById("demo").innerHTML = d; </script> Try it Yourself » Note If adding days, shifts the month or year, the changes are handled automatically by the Date object. Date Input - Parsing Dates If you have an input value (or any string), you can use the Date.parse() method to convert it to milliseconds. Date.parse() returns the number of milliseconds between the date and January 1, 1970: Example <script> var msec = Date.parse("March 21, 2012"); document.getElementById("demo").innerHTML = msec; </script> Try it Yourself » You can then use the number of milliseconds to convert it to a date object: Example <script> var msec = Date.parse("March 21, 2012"); var d = new Date(msec); document.getElementById("demo").innerHTML = d; </script> Try it Yourself » Compare Dates Dates can easily be compared. The following example compares today's date with January 14, 2100: Example var today, someday, text; today = new Date(); someday = new Date(); someday.setFullYear(2100, 0, 14); if (someday > today) { text = "Today is before January 14, 2100."; } else { text = "Today is after January 14, 2100."; } document.getElementById("demo").innerHTML = text; Try it Yourself »

JS Dates

JavaScript Dates « PreviousNext Chapter » The Date object lets you work with dates (years, months, days, minutes, seconds, milliseconds) Displaying Dates In this tutorial we use a script to display dates inside a <p> element with id="demo": Example <p id="demo"></p> <script> document.getElementById("demo").innerHTML = Date(); </script> Try it Yourself » The script above says: assign the value of Date() to the content (innerHTML) of the element with id="demo". Note You will learn how to display a date, in a more readable format, at the bottom of this page. Creating Date Objects The Date object lets us work with dates. A date consists of a year, a month, a week, a day, a minute, a second, and a millisecond. Date objects are created with the new Date() constructor. There are 4 ways of initiating a date: new Date() new Date(milliseconds) new Date(dateString) new Date(year, month, day, hours, minutes, seconds, milliseconds) Using new Date(), without parameters, creates a new date object with the current date and time: Example <script> var d = new Date(); document.getElementById("demo").innerHTML = d; </script> Try it Yourself » Using new Date(), with a date string, creates a new date object with the specified date and time: Example <script> var d = new Date("October 13, 2014 11:13:00"); document.getElementById("demo").innerHTML = d; </script> Try it Yourself » Using new Date(), with a number, creates a new date object with number of millisecond since 1970/01/01: Example <script> var d = new Date(0); document.getElementById("demo").innerHTML = d; </script> Try it Yourself » Note JavaScript dates are calculated in milliseconds from 01 January, 1970 00:00:00 Universal Time (UTC). One day contains 86,400,000 millisecond. Using new Date(), with 7 numbers, creates a new date object with the specified date and time: The 7 numbers specify the year, month, day, hour, minute, second, and millisecond, in that order: Example <script> var d = new Date(99,5,24,11,33,30,0); document.getElementById("demo").innerHTML = d; </script> Try it Yourself » Variants of the example above let us omit any of the last 4 parameters: Example <script> var d = new Date(99,5,24); document.getElementById("demo").innerHTML = d; </script> Try it Yourself » Note JavaScript counts months from 0 to 11. January is 0. December is 11. Date Methods When a Date object is created, a number of methods allow you to operate on it. Date methods allow you to get and set the year, month, day, hour, minute, second, and millisecond of objects, using either local time or UTC (universal, or GMT) time. The next chapter, of this tutorial, covers the date object's methods. Displaying Dates When you display a date object in HTML, it is automatically converted to a string, with the toString() method. Example <p id="demo"></p> <script> d = new Date(); document.getElementById("demo").innerHTML = d; </script> Is the same as: <p id="demo"></p> <script> d = new Date(); document.getElementById("demo").innerHTML = d.toString(); </script> Try it Yourself » The toUTCString() method converts a date to a UTC string (a date display standard). Example <script> var d = new Date(); document.getElementById("demo").innerHTML = d.toUTCString; </script> Try it Yourself » The toDateString() method converts a date to a more readable format: Example <script> var d = new Date(); document.getElementById("demo").innerHTML = d.toDateString; </script> Try it Yourself »

JS Errors

JavaScript Errors - Throw and Try to Catch « PreviousNext Chapter » The try statement lets you test a block of code for errors. The catch statement lets you handle the error. The throw statement lets you create custom errors. The finally statement lets you execute code, after try and catch, regardless of the result. Errors Will Happen! When executing JavaScript code, different errors can occur. Errors can be coding errors made by the programmer, errors due to wrong input, and other unforeseeable things: Example <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> try { adddlert("Welcome guest!"); } catch(err) { document.getElementById("demo").innerHTML = err.message; } </script> </body> </html> Try it Yourself » In the example above we have made a typo in the code (in the try block). The catch block catches the error, and executes code to handle it: JavaScript try and catch The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. The JavaScript statements try and catch come in pairs: try { Block of code to try } catch(err) { Block of code to handle errors } JavaScript Throws Errors When an error occurs, JavaScript will normally stop, and generate an error message. The technical term for this is: JavaScript will throw an error. The throw Statement The throw statement allows you to create a custom error. The technical term for this is: throw an exception. The exception can be a JavaScript String, a Number, a Boolean or an Object: throw "Too big"; // throw a text throw 500; // throw a number If you use throw together with try and catch, you can control program flow and generate custom error messages. Input Validation Example This example examines input. If the value is wrong, an exception (err) is thrown. The exception (err) is caught by the catch statement and a custom error message is displayed: <!DOCTYPE html> <html> <body> <p>Please input a number between 5 and 10:</p> <input id="demo" type="text"> <button type="button" onclick="myFunction()">Test Input</button> <p id="message"></p> <script> function myFunction() { var message, x message = document.getElementById("message"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "is Empty"; if(isNaN(x)) throw "not a number"; if(x > 10) throw "too high"; if(x < 5) throw "too low"; } catch(err) { message.innerHTML = "Input " + err; } } </script> </body> </html> Try it Yourself » The finally Statement The finally statement lets you execute code, after try and catch, regardless of the result: try { Block of code to try } catch(err) { Block of code to handle errors } finally { Block of code to be executed regardless of the try / catch result } Example function myFunction() var message, x; message = document.getElementById("message"); message.innerHTML = ""; x = document.getElementById("demo").value; try { if(x == "") throw "Empty"; if(isNaN(x)) throw "Not a number"; if(x > 10) throw "Too high"; if(x < 5) throw "Too low"; } catch(err) { message.innerHTML = "Error: " + err + "."; } finally { document.getElementById("demo").value = ""; } } Try it Yourself »

JS Loop for

JavaScript For Loop « PreviousNext Chapter » Loops can execute a block of code a number of times. JavaScript Loops Loops are handy, if you want to run the same code over and over again, each time with a different value. Often this is the case when working with arrays: Instead of writing: text += cars[0] + "<br>"; text += cars[1] + "<br>"; text += cars[2] + "<br>"; text += cars[3] + "<br>"; text += cars[4] + "<br>"; text += cars[5] + "<br>"; You can write: for (i = 0; i < cars.length; i++) { text += cars[i] + "<br>"; } Try it Yourself » Different Kinds of Loops JavaScript supports different kinds of loops: for - loops through a block of code a number of times for/in - loops through the properties of an object while - loops through a block of code while a specified condition is true do/while - also loops through a block of code while a specified condition is true The For Loop The for loop is often the tool you will use when you want to create a loop. The for loop has the following syntax: for (statement 1; statement 2; statement 3) { code block to be executed } Statement 1 is executed before the loop (the code block) starts. Statement 2 defines the condition for running the loop (the code block). Statement 3 is executed each time after the loop (the code block) has been executed. Example for (i = 0; i < 5; i++) { text += "The number is " + i + "<br>"; } Try it Yourself » From the example above, you can read: Statement 1 sets a variable before the loop starts (var i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). Statement 3 increases a value (i++) each time the code block in the loop has been executed. Statement 1 Normally you will use statement 1 to initiate the variable used in the loop (var i = 0). This is not always the case, JavaScript doesn't care. Statement 1 is optional. You can initiate many values in statement 1 (separated by comma): Example: for (i = 0, len = cars.length, text = ""; i < len; i++) { text += cars[i] + "<br>"; } Try it Yourself » And you can omit statement 1 (like when your values are set before the loop starts): Example: var i = 2; var len = cars.length; var text = ""; for (; i < len; i++) { text += cars[i] + "<br>"; } Try it Yourself » Statement 2 Often statement 2 is used to evaluate the condition of the initial variable. This is not always the case, JavaScript doesn't care. Statement 2 is also optional. If statement 2 returns true, the loop will start over again, if it returns false, the loop will end. Note If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser. Read about breaks in a later chapter of this tutorial. Statement 3 Often statement 3 increases the initial variable. This is not always the case, JavaScript doesn't care, and statement 3 is optional. Statement 3 can do anything like negative increment (i--), or larger increment (i = i + 15), or anything else. Statement 3 can also be omitted (like when you increment your values inside the loop): Example: var i = 0; len = cars.length; for (; i < len; ) { text += cars[i] + "<br>"; i++; } Try it Yourself » The For/In Loop The JavaScript for/in statement loops through the properties of an object: Example var person = {fname:"John", lname:"Doe", age:25}; var text = ""; var x; for (x in person) { text += person[x]; } Try it Yourself » The While Loop The while loop and the do/while loop will be explained in the next chapter.

JS Hoisting

JavaScript Hoisting « PreviousNext Chapter » Hoisting is JavaScript's default behavior of moving declarations to the top. JavaScript Declarations are Hoisted In JavaScript, a variable can be declared after it has been used. In other words; a variable can be used before it has been declared. Example 1 gives the same result as Example 2: Example 1 x = 5; // Assign 5 to x elem = document.getElementById("demo"); // Find an element elem.innerHTML = x; // Display x in the element var x; // Declare x Try it Yourself » Example 2 var x; // Declare x x = 5; // Assign 5 to x elem = document.getElementById("demo"); // Find an element elem.innerHTML = x; // Display x in the element Try it Yourself » To understand this, you have to understand the term "hoisting". Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function). JavaScript Initializations are Not Hoisted JavaScript only hoists declarations, not initializations. Example 1 does not give the same result as Example 2: Example 1 var x = 5; // Initialize x var y = 7; // Initialize y elem = document.getElementById("demo"); // Find an element elem.innerHTML = x + " " + y; // Display x and y Try it Yourself » Example 2 var x = 5; // Initialize x elem = document.getElementById("demo"); // Find an element elem.innerHTML = x + " " + y; // Display x and y var y = 7; // Initialize y Try it Yourself » Does it make sense that y is undefined in the last example? This is because only the declaration (var y), not the initialization (=7) is hoisted to the top. Because of hoisting, y has been declared before it is used, but because initializations are not hoisted, the value of y is undefined. Example 2 is the same as writing: Example var x = 5; // Initialize x var y; // Declare y elem = document.getElementById("demo"); // Find an element elem.innerHTML = x + " " + y; // Display x and y y = 7; // Assign 7 to y Try it Yourself » Declare Your Variables At the Top ! Hoisting is (to many developers) an unknown or overlooked behavior of JavaScript. If a developer doesn't understand hoisting, programs may contain bugs (errors). To avoid bugs, always declare all variables at the beginning of every scope. Since this is how JavaScript interprets the code, it is always a good rule. Note JavaScript in strict mode does not allow variables to be used if they are not declared. Study "using strict"; in the next chapter.

JS Conditions

JavaScript If...Else Statements « PreviousNext Chapter » Conditional statements are used to perform different actions based on different conditions. Conditional Statements Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this. In JavaScript we have the following conditional statements: Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed The if Statement Use the if statement to specify a block of JavaScript code to be executed if a condition is true. Syntax if (condition) { block of code to be executed if the condition is true } Note Note that if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error. Example Make a "Good day" greeting if the time is less than 20:00: if (time < 20) { greeting = "Good day"; } The result of greeting will be: Good day Try it Yourself » The else Statement Use the else statement to specify a block of code to be executed if the condition is false. if (condition) { block of code to be executed if the condition is true } else { block of code to be executed if the condition is false } Example If the time is less than 20:00, create a "Good day" greeting, otherwise "Good evening": if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; } The result of greeting will be: Good day Try it Yourself » The else if Statement Use the else if statement to specify a new condition if the first condition is false. Syntax if (condition1) { block of code to be executed if condition1 is true } else if (condition2) { block of code to be executed if the condition1 is false and condition2 is true } else { block of code to be executed if the condition1 is false and condition2 is false } Example If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a "Good day" greeting, otherwise a "Good evening": if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; } The result of x will be: Good day Try it Yourself » Examples More Examples Random link This example will write a link to either W3Schools or to the World Wildlife Foundation (WWF). By using a random number, there is a 50% chance for each of the links.

JS Math

JavaScript Math Object « PreviousNext Chapter » The Math object allows you to perform mathematical tasks on numbers. The Math Object The Math object allows you to perform mathematical tasks. The Math object includes several mathematical methods. One common use of the Math object is to create a random number: Example Math.random(); // returns a random number Try it yourself » Note Math has no constructor. No methods have to create a Math object first. Math.min() and Math.max() Math.min() and Math.max() can be used to find the lowest or highest value in a list of arguments: Example Math.min(0, 150, 30, 20, -8); // returns -8 Try it yourself » Example Math.max(0, 150, 30, 20, -8); // returns 150 Try it yourself » Math.random() Math.random() returns a random number between 0 and 1: Example Math.random(); // returns a random number Try it yourself » Math.round() Math.round() rounds a number to the nearest integer: Example Math.round(4.7); // returns 5 Math.round(4.4); // returns 4 Try it yourself » Math.ceil() Math.ceil() rounds a number up to the nearest integer: Example Math.ceil(4.4); // returns 5 Try it yourself » Math.floor() Math.floor() rounds a number down to the nearest integer: Example Math.floor(4.7); // returns 4 Try it yourself » Math.floor() and Math.random() can be used together return a random number between 0 and 10: Example Math.floor(Math.random() * 11); // returns a random number between 0 and 10 Try it yourself » Math Constants JavaScript provides 8 mathematical constants that can be accessed with the Math object: Example Math.E; // returns Euler's number Math.PI // returns PI Math.SQRT2 // returns the square root of 2 Math.SQRT1_2 // returns the square root of 1/2 Math.LN2 // returns the natural logarithm of 2 Math.LN10 // returns the natural logarithm of 10 Math.LOG2E // returns base 2 logarithm of E Math.LOG10E // returns base 10 logarithm of E Try it yourself » Math Object Methods Method Description abs(x) Returns the absolute value of x acos(x) Returns the arccosine of x, in radians asin(x) Returns the arcsine of x, in radians atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians atan2(y,x) Returns the arctangent of the quotient of its arguments ceil(x) Returns x, rounded upwards to the nearest integer cos(x) Returns the cosine of x (x is in radians) exp(x) Returns the value of Ex floor(x) Returns x, rounded downwards to the nearest integer log(x) Returns the natural logarithm (base E) of x max(x,y,z,...,n) Returns the number with the highest value min(x,y,z,...,n) Returns the number with the lowest value pow(x,y) Returns the value of x to the power of y random() Returns a random number between 0 and 1 round(x) Rounds x to the nearest integer sin(x) Returns the sine of x (x is in radians) sqrt(x) Returns the square root of x tan(x) Returns the tangent of an angle

JS Number methods

JavaScript Number Methods « PreviousNext Chapter » Numbers methods help you to work with numbers. Global Methods JavaScript global functions can be used on all JavaScript data types. These are the most relevant methods, when working with numbers: Method Description Number() Returns a number, converted from its argument. parseFloat() Parses its argument and returns a floating point number parseInt() Parses its argument and returns an integer Number Methods JavaScript number methods are methods that can be used on numbers: Method Description toString() Returns a number as a string toExponential() Returns a string, with a number rounded and written using exponential notation. toFixed() Returns a string, with a number rounded and written with a specified number of decimals. toPrecision() Returns a string, with a number written with a specified length valueOf() Returns a number as a number Note All number methods return a new variable. They do not change the original variable. The toString() Method toString() returns a number as a string. All number methods can be used on any type of numbers, literals, variables, or expressions: Example var x = 123; x.toString(); // returns 123 from variable x (123).toString(); // returns 123 from literal 123 (100 + 23).toString(); // returns 123 from expression 100 + 23 Try it yourself » The toExponential() Method toExponential() returns a string, with a number rounded and written using exponential notation. A parameter defines the number of character behind the decimal point: Example var x = 9.656; x.toExponential(2); // returns 9.66e+0 x.toExponential(4); // returns 9.6560e+0 x.toExponential(6); // returns 9.656000e+0 Try it yourself » The parameter is optional. If you don't specify it, JavaScript will not round the number. The toFixed() Method toFixed() returns a string, with the number written with a specified number of decimals: Example var x = 9.656; x.toFixed(0); // returns 10 x.toFixed(2); // returns 9.66 x.toFixed(4); // returns 9.6560 x.toFixed(6); // returns 9.656000 Try it yourself » Note toFixed(2) is perfect for working with money. The toPrecision() Method toPrecision() returns a string, with a number written with a specified length: Example var x = 9.656; x.toPrecision(); // returns 9.656 x.toPrecision(2); // returns 9.7 x.toPrecision(4); // returns 9.656 x.toPrecision(6); // returns 9.65600 Try it yourself » Converting Variables to Numbers There are 3 JavaScript functions that can be used to convert variables to numbers: The Number() method The parseInt() method The parseFloat() method These methods are not number methods, but global JavaScript methods. The Number() Method Number(), can be used to convert JavaScript variables to numbers: Example x = true; Number(x); // returns 1 x = false; Number(x); // returns 0 x = new Date(); Number(x); // returns 1404568027739 x = "10" Number(x); // returns 10 x = "10 20" Number(x); // returns NaN Try it yourself » The parseInt() Method parseInt() parses a string and returns a whole number. Spaces are allowed. Only the first number is returned: Example parseInt("10"); // returns 10 parseInt("10.33"); // returns 10 parseInt("10 20 30"); // returns 10 parseInt("10 years"); // returns 10 parseInt("years 10"); // returns NaN Try it yourself » If the number cannot be converted, NaN (Not a Number) is returned. The parseFloat() Method parseFloat() parses a string and returns a number. Spaces are allowed. Only the first number is returned: Example parseFloat("10"); // returns 10 parseFloat("10.33"); // returns 10.33 parseFloat("10 20 30"); // returns 10 parseFloat("10 years"); // returns 10 parseFloat("years 10"); // returns NaN Try it yourself » If the number cannot be converted, NaN (Not a Number) is returned. The valueOf() Method valueOf() returns a number as a number. Example var x = 123; x.valueOf(); // returns 123 from variable x (123).valueOf(); // returns 123 from literal 123 (100 + 23).valueOf(); // returns 123 from expression 100 + 23 Try it yourself » In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object). The valueOf() method is used internally in JavaScript to convert Number objects to primitive values. There is no reason to use it in your code. Note In JavaScript, all data types have a valueOf() and a toString() method. Complete JavaScript Number Reference For a complete reference, go to our Complete JavaScript Number Reference. The reference contains descriptions and examples of all Number properties and methods.

JS Performance

JavaScript Performance « PreviousNext Chapter » How to speed up your JavaScript code. Reduce Activity in Loops Loops are often used in programming. Every statement inside a loop will be executed for each iteration of the loop. Search for statements or assignments that can be placed outside the loop. Reduce DOM Access Accessing the HTML DOM is very slow, compared to other JavaScript statements. If you expect to access a DOM element several times, access it once, and use it as a local variable: Example obj = document.getElementByID("demo"); obj.innerHTML = "Hello"; Try it yourself » Reduce DOM Size Keep the number of elements in the HTML DOM small. This will always improve page loading, and speed up rendering (page display), especially on smaller devices. Every attempt to search the DOM (like getElementsByTagName) is will benefit from a smaller DOM. Avoid Unnecessary Variables Don't create new variables if you don't plan to save values. Often you can replace code like this: var fullName = firstName + " " + lastName; document.getElementById("demo").innerHTML = fullName; With this: document.getElementById("demo").innerHTML = firstName + " " + lastName Delay JavaScript Loading Putting your scripts at the bottom of the page body, lets the browser load the page first. While a script is downloading, the browser will not start any other downloads. In addition all parsing and rendering activity might be blocked. Note The HTTP specification defines that browsers should not download more than two components in parallel. An alternative is to use defer="true" in the script tag. The defer attribute specifies that the script should be executed before the page has finished parsing, but it only works for external scripts. If possible, you can add your script to the page by code, after the page has loaded: Example <script> window.onload = downScripts; function downScripts() { var element = document.createElement("script"); element.src = "myScript.js"; document.body.appendChild(element); } </script> Avoid Using with Avoid using the with keyword. It has a negative effect on speed. It also clutters up JavaScript scopes. The with keyword is not allowed in strict mode.

JS Regular Expressions

JavaScript Regular Expressions « PreviousNext Chapter » A regular expression is a sequence of characters that forms a search pattern. The search pattern can be used for text search and text replace operations. What Is a Regular Expression? A regular expression is a sequence of characters that forms a search pattern. When you search for data in a text, you can use this search pattern to describe what you are searching for. A regular expression can be a single character, or a more complicated pattern. Regular expressions can be used to perform all types of text search and text replace operations. Syntax /pattern/modifiers; Example: var patt = /w3schools/i Example explained: /w3schools/i is a regular expression. w3schools is a pattern (to be used in a search). i is a modifier (modifies the search to be case-insensitive). Using String Methods In JavaScript, regular expressions are often used with the two string methods: search() and replace(). The search() method uses an expression to search for a match, and returns the position of the match. The replace() method returns a modified string where the pattern is replaced. Using String search() With a Regular Expression Example Use a regular expression to do a case-insensitive search for "w3schools" in a string: var str = "Visit W3Schools"; var n = str.search(/w3schools/i); The result in n will be: 6 Try it Yourself » Using String search() With String The search method will also accept a string as search argument. The string argument will be converted to a regular expression: Example Use a string to do a search for "W3schools" in a string: var str = "Visit W3Schools!"; var n = str.search("W3Schools"); Try it Yourself » Use String replace() With a Regular Expression Example Use a case insensitive regular expression to replace Microsoft with W3Schools in a string: var str = "Visit Microsoft!"; var res = str.replace(/microsoft/i, "W3Schools"); The result in res will be: Visit W3Schools! Try it Yourself » Using String replace() With a String The replace() method will also accept a string as search argument: var str = "Visit Microsoft!"; var res = str.replace("Microsoft", "W3Schools"); Try it Yourself » Did You Notice? Note Regular expression arguments (instead of string arguments) can be used in the methods above. Regular expressions can make your search much more powerful (case insensitive for example). Regular Expression Modifiers Modifiers can be used to perform case-insensitive more global searches: Modifier Description i Perform case-insensitive matching g Perform a global match (find all matches rather than stopping after the first match) m Perform multiline matching Regular Expression Patterns Brackets are used to find a range of characters: Expression Description [abc] Find any of the characters between the brackets [0-9] Find any of the digits between the brackets (x|y) Find any of the alternatives separated with | Metacharacters are characters with a special meaning: Metacharacter Description \d Find a digit \s Find a whitespace character \b Find a match at the beginning or at the end of a word \uxxxx Find the Unicode character specified by the hexadecimal number xxxx Quantifiers define quantities: Quantifier Description n+ Matches any string that contains at least one n n* Matches any string that contains zero or more occurrences of n n? Matches any string that contains zero or one occurrences of n Using the RegExp Object In JavaScript, the RegExp object is a regular expression object with predefined properties and methods. Using test() The test() method is a RegExp expression method. It searches a string for a pattern, and returns true or false, depending on the result. The following example searches a string for the character "e": Example var patt = /e/; patt.test("The best things in life are free!"); Since there is an "e" in the string, the output of the code above will be: true Try it Yourself » You don't have to put the regular expression in a variable first. The two lines above can be shortened to one: /e/.test("The best things in life are free!") Using exec() The exec() method is a RegExp expression method. It searches a string for a specified pattern, and returns the found text. If no match is found, it returns null. The following example searches a string for the character "e": Example 1 /e/.exec("The best things in life are free!"); Since there is an "e" in the string, the output of the code above will be: e Try it Yourself »

JS Data Types

JavaScript Strings A string is a variable which stores a series of characters like "John Doe". Strings are written with quotes. You can use single or double quotes: Example var carName = "Volvo XC60"; // Using double quotes var carName = 'Volvo XC60'; // Using single quotes You can use quotes inside a string, as long as they don't match the quotes surrounding the string: Example var answer = "It's alright"; // Single quote inside double quotes var answer = "He is called 'Johnny'"; // Single quotes inside double quotes var answer = 'He is called "Johnny"'; // Double quotes inside single quotes ============================================ The typeof Operator You can use the JavaScript typeof operator to find the type of a JavaScript variable. Example typeof "John" // Returns string typeof 3.14 // Returns number typeof false // Returns boolean typeof [1,2,3,4] // Returns object typeof {name:'John', age:34} // Returns object

JS Switch

JavaScript Switch Statement « PreviousNext Chapter » The switch statement is used to perform different action based on different conditions. The JavaScript Switch Statement Use the switch statement to select one of many blocks of code to be executed. Syntax switch(expression) { case n: code block break; case n: code block break; default: default code block } This is how it works: The switch expression is evaluated once. The value of the expression is compared with the values of each case. If there is a match, the associated block of code is executed. Example Use today's weekday number to calculate weekday name: (Sunday=0, Monday=1, Tuesday=2, ...) switch (new Date().getDay()) { case 0: day = "Sunday"; break; case 1: day = "Monday"; break; case 2: day = "Tuesday"; break; case 3: day = "Wednesday"; break; case 4: day = "Thursday"; break; case 5: day = "Friday"; break; case 6: day = "Saturday"; break; } The result of day will be: Sunday Try it Yourself » The break Keyword When the JavaScript code interpreter reaches a break keyword, it breaks out of the switch block. This will stop the execution of more execution of code and/or case testing inside the block. Note When a match is found, and the job is done, it's time for a break. There is no need for more testing. The default Keyword The default keyword specifies the code to run if there is no case match: Example If today is neither Saturday nor Sunday, write a default message: switch (new Date().getDay()) { case 6: text = "Today is Saturday"; break; case 0: text = "Today is Sunday"; break; default: text = "Looking forward to the Weekend"; } The result of text will be: Today is Sunday Try it Yourself » Common Code and Fall-Through Sometimes, in a switch block, you will want different cases to use the same code, or fall-through to a common default. Note from the next example, that cases can share the same code block, and that the default case does not have to be the last case in a switch block: Example switch (new Date().getDay()) { case 1: case 2: case 3: default: text = "Looking forward to the Weekend"; break; case 4: case 5: text = "Soon it is Weekend"; break; case 0: case 6: text = "It is Weekend"; } Try it Yourself »

JS Loop While

JavaScript While Loop « PreviousNext Chapter » Loops can execute a block of code as long as a specified condition is true. The While Loop The while loop loops through a block of code as long as a specified condition is true. Syntax while (condition) { code block to be executed } Example In the following example, the code in the loop will run, over and over again, as long as a variable (i) is less than 10: Example while (i < 10) { text += "The number is " + i; i++; } Try it Yourself » Note If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser. The Do/While Loop The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. Syntax do { code block to be executed } while (condition); Example The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false, because the code block is executed before the condition is tested: Example do { text += "The number is " + i; i++; } while (i < 10); Try it Yourself » Do not forget to increase the variable used in the condition, otherwise the loop will never end! Comparing For and While If you have read the previous chapter, about the for loop, you will discover that a while loop is much the same as a for loop, with statement 1 and statement 3 omitted. The loop in this example uses a for loop to collect the car names from the cars array: Example cars = ["BMW","Volvo","Saab","Ford"]; var i = 0; var text = ""; for (;cars[i];) { text += cars[i] + "<br>"; i++; } Try it Yourself » The loop in this example uses a while loop to collect the car names from the cars array: Example cars = ["BMW","Volvo","Saab","Ford"]; var i = 0; var text = ""; while (cars[i]) { text += cars[i] + "<br>"; i++; } Try it Yourself »

How to create multiple style sheets?

Multiple Style Sheets If some properties have been set for the same selector in different style sheets, the values will be inherited from the more specific style sheet. For example, assume that an external style sheet has the following properties for the h3 selector: h3 { color: red; text-align: left; font-size: 8pt; } then, assume that an internal style sheet also has the following properties for the h3 selector: h3 { text-align: right; font-size: 20pt; } If the page with the internal style sheet also links to the external style sheet the properties for the h3 element will be: color: red; text-align: right; font-size: 20pt;

How do you make a password filed?

Password Field <input type="password"> defines a password field: <form> Password: <input type="password" name="pwd"> </form> How the HTML code above looks in a browser: Password: Note: The characters in a password field are masked (shown as asterisks or circles).

How do you create entities?

Result Description Entity Name Entity Number non-breaking space &nbsp; &#160; < less than < < > greater than > > & ampersand & & ¢ cent &cent; &#162; £ pound &pound; &#163; ¥ yen &yen; &#165; € euro &euro; &#8364; © copyright &copy; &#169; ® registered trademark &reg; &#174;

objects

Spaces and line breaks are not important. An object declaration can span multiple lines: Example var person = { firstName:"John", lastName:"Doe", age:50, eyeColor:"blue" }; ============================================ Accessing Object Properties You can access the object properties in two ways: Example person.lastName; person["lastName"];

How do you make a submit field?

Submit Button <input type="submit"> defines a submit button. A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. The file defined in the action attribute usually does something with the received input: <form name="input" action="demo_form_action.asp" method="get"> Username: <input type="text" name="user"> <input type="submit" value="Submit"> </form> How the HTML code above looks in a browser: Username:

What are some attributes for tables?

Tag Description <table> Defines a table <th> Defines a header cell in a table <tr> Defines a row in a table <td> Defines a cell in a table <caption> Defines a table caption <colgroup> Specifies a group of one or more columns in a table for formatting <col> Specifies column properties for each column within a <colgroup> element <thead> Groups the header content in a table <tbody> Groups the body content in a table <tfoot> Groups the footer content in a table

Change HTML styles

document.getElementById("demo").style.fontSize = "25px"; ============================================ <!DOCTYPE html> <html> <body> <h1>My First JavaScript</h1> <p id="demo">JavaScript can change the style of an HTML element.</p> <script> function myFunction() { var x = document.getElementById("demo"); x.style.fontSize = "25px"; x.style.color = "red"; } </script> <button type="button" onclick="myFunction()">Click Me!</button> </body> </html>

How to create padding in CSS

p { padding-top: 25px; padding-bottom: 25px; padding-right: 50px; padding-left: 50px; }

How do you create symbols?

p>I will display &euro;</p> <p>I will display &#8364;</p> <p>I will display &#x20AC;</p> Will display as: I will display € I will display € I will display €

How do you make different font sizes?j

body { font-size: 100%; } h1 { font-size: 2.5em; } h2 { font-size: 1.875em; } p { font-size: 0.875em; }

what are some attributes of HTML encode?

http HyperText Transfer Protocol Common web pages starts with http://. Not encrypted https Secure HyperText Transfer Protocol Secure web pages. All information exchanged are encrypted ftp File Transfer Protocol For downloading or uploading files to a website. Useful for domain maintenance file A file on your computer


Set pelajaran terkait

Learning Environment - Face to Face & Virtual Learning

View Set

Macroeconomics Exam 2 Launchpad HW

View Set