Introduction
JavaScript is a scripting language, weakly typed, no compilation needed, runs in browsers. Completely unrelated to Java.
Components:
| Component | Purpose |
|---|---|
| ECMA Script | Core JS syntax foundation |
| BOM | Browser Object Model, browser operations |
| DOM | Document Object Model, page element manipulation |
Writing Locations
- Inline:
<script>alert("inline")</script> - External:
<script src="js/index.js"></script> - Inline handler:
<input type="button" value="ClickMe" onclick="alert('hello');">
Data Types
number, string, boolean, object, undefined
var a = 1; var b = "hello"; var c = true;
typeof a; // returns the type
Operators
Arithmetic: + - * / % ++ --
Relational: > >= < <= != == ===
Logical: && || !
Ternary: condition ? expr1 : expr2
Control Flow
if (score >= 90) { alert("Excellent"); }
else if (score >= 80) { alert("Good"); }
else { alert("Fail"); }
switch(parseInt(score/10)) {
case 10: case 9: alert("Excellent"); break;
case 8: alert("Good"); break;
default: alert("Fail");
}
while(condition){ body; }
do { body; } while(condition);
for(var i=0; i<10; i++){ body; }
Functions
function name(params) { body; return value; }
var fn = function(params) { body; }; // anonymous function
Image Carousel
<img id="img" src="images/01.jpg">
<script>
var img = document.getElementById("img");
var count = 1;
function changeImageSrc() {
count++;
img.src = "images/0" + count + ".jpg";
if (count == 8) count = 0;
}
window.setInterval(changeImageSrc, 2000);
</script>
JS Events
Format: element.event = handler
| Event | Description |
|---|---|
| onload | Page/image loaded |
| onclick | Mouse click |
| onsubmit | Form submit |
| onblur/onfocus | Element focus change |
| onkeydown/up | Keyboard press/release |
| onmouseover/out | Mouse enter/leave |
| onchange | Content changed |