Javascript Introduction

ACM Student Chapter
Dr. David Cline

Thursday April 7, 2016, 5:30, 206 MSCS


HTML structure


Common HTML tags


Some GUI elements


Basic HTML 5 document


Javascript overview and features


Simple page that changes based on button presses.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Javascript Example</title>
</head>
<body>
    <h1 id="demo">Javascript</h1>
    <button type="button" onclick="clickFunction()">click</button>

    <script>
    var x = 0; // global variable

    function clickFunction() // function called when the button is clicked
    {
        var element = document.getElementById("demo");
        if (x % 2 == 0) element.innerHTML = "Javascript is fun";
        else element.innerHTML = "Javascript is super fun";
        x++;
    }
    </script>
</body>
</html> 

Javascript variables


Javascript basic types


Javascript operators


Javascript arrays functionality

var cars = ["Saab", "Volvo", "BMW"]; 
cars[cars.length] = "Ford"; // adds "Ford" to the end of the array
cars[0] = "GMC"; // replaces element 0 with "GMC"
cars.delete(0); // replaces element 0 with undefined

cars.push("GMC"); // pushes "GMC" on the end
cars.pop(); // removes last element

cars.unshift("GMC"); // adds "GMC" to front
cars.shift(); // removes first element

var compacts = cars.slice(2,4); // extract elements 2 to 4 (not inclusive)

cars.splice(2, 3); // remove 3 elements starting at element 2
cars.splice(2, 1, "Ford", "GMC");  // remove and replace with "Ford" and "GMC"

var myChildren = myGirls.concat(myBoys); // concatenate 2 arrays

cars.sort(); // sorts strings
cars.reverse();

Javascript objects examples

var person = {firstName:"John", age:50};

// Javascript converts a standard array into an object if you
// add something at a non-numeric index.
var person = [];
person["firstName"] = "John";
person["age"] = 46;

Javascript functions examples


Javascript loops


DOM and input examples

    function myFunction() {
       x = document.getElementById("demo") // Find the element
       x.style.color = "#ff0000";          // Change the style
    }

    val = document.getElementById("txt").value;

    <input id="txt" type="text" onKeyUp="typeFunction()">

    <input id="txt" type="text" onKeyDown="if (event.keyCode == 13) typeFunction()">