Website: JavaScript.doc - ZhaochengLi/Zhaocheng-s GitHub Wiki

Introduction to JavaScript!

Introduction to JavaScript

Intro

JavaScript is the programming language that adds interactively and custom behaviors to our sites. It is a client-side scripting language, which means it runs on the user's machine and not on the server, as other web programming languages such as PHP and Ruby do. That means JS is reliant on the browser's capabilities and settings. It may not even be available at all, either because the user has chosen to turn it off or because the device does not support it.

JS is also what is known as a dynamic and loosely typed programming language.

Characters

  • It is not related to Java.
  • It is a lightweight but incredibly powerful scripting language.
  • It is a dynamic programming language, it does not need to be run through any form of compiler that interprets our human-readable code into something the browser can understand. The browser effectively reads the code the same way we do and interprets it on the fly.
  • It is also loosely typed. It means we do not necessarily have to tell JS what a variable is. If we are setting a variable to a value of 5, we do not have to programmatically specify that varialbe as a number.

Waht it can do

  • Suggest the complete term a user might be entering in a search box as the types.
  • Request content and information from the server and inject it into the current document as needed, without reloading the entire page --- this is commonly referred to as "Ajax".
  • Show and hide content based on a user clicking on a link or heading, to create a "collapsible" content area.
  • Test for browsers' individual features and capabilities. Fro example, one can test for the presence of "touch events", indicating that the user is interacting with the page through a mobile device's browser, and add more touch-friendly styles and interaction methods.
  • Fill in gaps where a browser's built-in functionality falls apart, or add some of the features found in newer browsers to older browsers. These kinds of scripts are usually called shims or polyfills.
  • Load an image or content in a custom styled "lightbox" --- isolated on the page using CSS --- after a user clicks on a thumbnails version of the image.

Adding JS to a page

Just like CSS, you can either embed it right in a document or keep it in an external file and link it to the page, using script element.

  • Embedded scripts:

      <script>
          ... JS code goes here
      </script>
    
  • External scripts:

      <script src="my_script.js"></script>
    
  • Script placement: the script element can go anywhere in the document, but the most common places for scripts are in the head of the document and at the very end of the body. It is recommended that you don't sprinkle them throughout the document, because they would be diffcult to find and maintain.

The Anatomy of s Script

Originally, JS's functionality was mostly limited to the crude methods of interaction with the user.

  • We can use alert() to provide user feedback by pushing a notification to a user and
  • confirm() to ask a user to approve or decline an action.
  • We also use prompt() to request user's input. Now, JS has evolved much better and less bonoxious.

The basic syntactical rules

  • Statement. A script is made up of a series of statement. A statement is a command that tell the browser what to do. For example, alert("Thank you."); is a statement that makes the browser display an alert with the phrase "Thank you".

  • Do not forget the semicolon at the end of each statement.

  • Comments. Single line comments with // single line comments, while multi-line comments with /* Multiple lines here.*/

  • Variables. A variable in JS is like a information container, you can name it and then assign it a value. The value can be anything, such as a number, a text string, an element in the DOM, or a function.

      // declaration
      var foo = 5;
    
  • You can change the value of a variable at any time by re-declaring it any where in your script. Remember that JS is case-sensitive.

  • Data types.

    • Undefined. If we declare a variable without giving it a value, it becomes "undefined".

        var foo;
      
    • Null. Similar to the above, assigning a variable "null" means "Define this variable, but give it no inherit value."

        var foo = null;
      
    • Numbers.

        var foo = 5;
        alert(foo+foo); // it returns 10
      
    • Strings. This is basically lines of text.

        var foo = "Bye";
        alert(foo+foo); // it returns "ByeBye"
      
        // when you concatenate a string and a number, the number is treated as string.
        var num = 5;
        var str = "hello";
        alert(num+str); // it returns "5hello"
      
    • Booleans. There are only two value: true and false

        var foo = false;
      
  • Arrays. An array is a group of multiple values (called members) that can be assigned to a single variable. The value in an array are said to be indexed, meaning you can refer to them by number according to the order in which they appear in the list. The first number is given to the index number 0.

          var foo = [5, "hello", "120"];
          alert(foo[0]) // 5
          alert(foo[1]) // "hello"
    
  • Comparison operators

    • ==, is euqal to;

    • !=, is not equal to;

    • ===, is identical to (euqal to and of the same data type);

    • !==, is not identical to;

    • >, is greater than;

    • >=, is greater than or euqal to;

    • <, is less than;

    • <=, is less thsn or equal to;

        alert(5 == 5); // "true"
        alert(5 != 6); // "true"
        alert(5 < 1);  // "false"
        alert("5" == 5); // "true"
        alert("5" === 5); // "false"
        alert("5" !== 5); // "true"
      
  • Machematical operators

    • +=, adds the value to itself;
    • ++, increases the value of a number by 1;
    • --, decreases the value of a number by 1;
  • if/else statement

      if(true){
          // do something;
      }
      else{
          // do something else;
      }
    
  • loops

      // for(initialize the variable; test the condition; alter the value;){ .. do something .. }
      for (var i=0; i<=2; i++){ // do something; }
    
    • item.length: this is a built-in function to determine the length of an array.
  • Functions. A function is a bit of code that does not run until it is referenced or called.

      function func_name (func_arguments, optional){
          // code to execute;
          return something;
      }
    
  • Variable scope and the var keyword There are times when you'll want a variable that you've defined within a function to be available anywhere throughout your script. Other times, you want to restrict it and make it available only to the function it live in. This notion of the availability of the variable is known as scope. A variable that can be used by any of the scripts on your page is globally scoped, and a variable that's available only within its parent function is locally scoped.

JavaScript variables use functions to manage their scope. If a variable is defined outside of a function, it will be globally scoped and available to all scripts. When you define a variable within a function and you want it to be used only by that function, you can flag it as locally scoped by proceeding the variable name with the var keyword.

    var foo = "values";

and to expose a variable within a function to the global scope, we omit the var keyword and simply define the variable:

    foo = "value";

here is an example:

    function double(num){
        total = num + num;
        return total;
    }
    var total = 20;
    var number = double(20);
    alert(total); // alerts 40 since we declare it globally. It "leaked out"

Remember we can not control all the code in play on our page. It is very common for pages to include code written by third parties, for example:

  • scripts to render advertisements;
  • user-tracking and analytics scripts;
  • social media "share" buttons;

The browser object

In addition to control elements on a web page, JS also gives you access to and the ability to manipulate the parts of the browser window itself. For example, you might want to get or replace thr URL that is in the browser's address bar, or open or close a browser window. In JS, the browser is known as the window object. The window object has a number of properties and methods that we can use to interact with it. Actually the function alert() is actually one of the standard browser object methods. Here are some properties below:

Property/Methods Description
event Represents the state of an event
history Contains the URLs the user has visited within a browser window
location Gives read/write access to the URL in the address bar
status Sets or returns the text in the status bar of the window
alert() Displays an alert box with a specified message and an OK button
close() Closes the current window
confirm() Displays a dialog box with a specified message and an OK and a Cancel button
focus() Sets focus on the current window

Events

JS can access objects in the page and the browser window. Moreover, it is also "listening" for certain events to happen. An event is an action that can be detected with JS, such as when the document loads or when the user clicks on an element or just moves the mouse over it. HTML 4.0 made it possible for a script to be tied to events on the page whether initiated by the user, the browser itself, or other scripts. This is known as event binding.

In scripts, an event is identified by an event handler. For example, the onload event handler triggers a script when the document loads, and the onclick and onmouseover handlers trigger a script when the user clicks or mouses over an element, respectively.

Event Handler Event Description
onblur An element loses focus
onchange The content of a form field changes
onclick The mouse clicks an object
onerror An error occurs when the document or an image loads
onfocus An element gets focus
onkeydown A key on the keyboard is pressed
onkeypress A key on the keyboard is pressed or held down
onkeyup A key on the keyboard is released
onload A page or an image is finished loading
onmousedown A mouse button is pressed
onmousemove The mouse is moved
onmouseout The mouse is moved off an element
onmouseover The mouse is moved over an element
onmouseup A mouse button is released
onsubmit The submit button is clicked in a form

There are 3 common methods for applying event handlers to items within our pages:

  • As an HTML attribute;
  • As a method attached to the element
  • Using addEventListener

In the examples of the latter two approaches, we will use the window object. Any events we attach to window apply to the entire document. We will be using onclick event in all of those as well.

As an HTML attribute
    <body onclick="myFunction();"> 
    // myFunction will now run when the user clicks anything within "body"

This way is functional, but antiquated. We should avoid doing this just like we avoid using style attributes in our markup to apply styles to individual elements. In this case, it blurs the line between the semantic layer and behavioral layers of our pages, and acn quickly lead to a maintenance nightmare.

As a method

It is also a dated approach, although it does keep thing strictly within our scripts. We can also attach funtions using helpers already built into JS:

    window.onclick = myFunction;
    // myFunction will run when the user clicks anything within the browser window.

This approach has the benefit of both simplicity and ease of maintenance, but does have a fairly major drawback: we can bind only one event at a time with this method.

    window.onclick = myFunction;
    window.onclick = myOtherFunction;

Then the second binding overwrites the first, so when the user clicks the browser window, only myOtherFunction will run. The reference to myFunction is thrown away.

addEventListener

Although a bit complex at first glance, this approach allows us to keep our logic within our scripts and allows us to perform multiple bindings on a single object. We start by calling the addEventListener method of the target object, and then specify the event in question and the function to be executed as two arguments.

    window.addEventListener("click", myFunction); // we omit "on", syntax change
    // or also
    window.addEventListener("click", function(e){// do sth.});

Using JavaScript

We will take a look at some ways that we can put JS to use in modern web design. We will explore DOM scripting, which allows us to manipulate the elements, attributes, and text on a page. You will also learn about "polyfills", which provide older browsers with modern features and normalize functionality. Some JS libraries will also be introduced to make developers' lives easier with collections of polyfills and shortcuts for common tasks.

Meet the DOM

The Document Object Model (DOM for short) gives us a way to access and manipulate the content of a document. We commonly use it for HTML, but it worked with any XML language as well.

The DOM is a programming interface (an API) for HTML and XML pages. It provides a structured map of the document, as well as a set of methods to interface with the elements contained therein. Effectively, it translates our markup into a format that JS (and other languages) can understand. Basically, the DOM serves as a map to all the elements on a page. We can use it to find elements by their names or attributes, then add, modify, or delete elements and their content.

Without the DOM, JS wouldn't have any sense of a document's contents -- and by that, I mean the entirety of the document's contents. Everything from the page's doctype to each individual letter in the text can be accessed via the DOM and manipulated with JS.

The Node Tree

A simple way to think of the DOM is in terms of the document tree. You saw document in this way when you were learning about CSS selectors

    <html>
        <head>
            <title>Document Title</title>
            <meta charset="utf-8">
        </head>
        <body>
            <div>
                <h2>Subhead</h2>
                <p>Paragraph text with a <a href="foo,html">Link</a> Here.</p>
            </div>
            <div>
                <p>More text here</p>
            </div>
        </body>
    </html>

into a document tree.

Each element within the page is referred to as a node. If you think of DOM as a tree, then each node is an individual branch that can contain further branches. But the DOM allows deeper access the the content than CSS because it treats the actual content as a node as well. The elements, the attributes, and the contens are all ndoes in the DOM's node tree.

It also provides a standardized set of methods and functions through which JS can interact with the elements on our page. Most DOM scripting involves reading from and writing to the document. There are several ways to use the DOM to find what you want in a document. Let's go over some specific methods we can use for accessing objects defined by the DOM (also calling "crawling the DOM" or "traversing the DOM"), as well as some methods for manipulating those elements.

Accessing DOM nodes
  • the document object in the DOM identifies the page itself, and more often than not will serve as then starting point for our DOM crawling. It comes with a number of standard properties and methods for accessing collections of elements. For example, the length property is a standard property of all arrays. The document object comes with a number of built-in properties containing information about the document.

  • for the rest of the learing process, I will also work with a JS file to practice. First of all, try to find the element that has the id value "beginner", find the HTML content within that element (innerHTML), and save those contents to a variable foo.

      var foo = document.getElementById("beginner").innerHTML;
    

There are several ways of accessing nodes in the document

  • By element name: getElementByTagName(), this method retrieves any element or elements you specify as an argument.

      var paragraphs = document.getElementByTagName("p");
      paragraphs[0] is a reference to the first paragraph in the document, similarly,
      paragraphs[1] refers the second paragraph, and so on. Then we can use it in a loop such as
      for(var i=0; i<paragraphs.length; i++){
          // do something with paragraphs[i];
      }
    
  • By id attribute value: getElementById(), it returns a single element based on that element's ID(the value of its id attribute), which we provide to the method as an argument. For example, to access this particular image,

      <image src="photo.jpg" alt="" id="lead-photo">
      // then with id we can access
      var photo=document.getElementById("lead-photo");
    
  • By class attribute value: getElementByClassName(), this allows you to access nodes in the document based on the value of a class attribute. For example, this statement assigns any element with a class value of "column-a" to the variable firstColumn so it can be accessed easily from within a script.

      var firstColumn = document.getElementByClassName("column-a");
    

Like getElementByTagName, this returns a nodeList that we can reference by index or loop through one at a time.

  • By selector: querySelectorAll(), it allows you to access nodes of the DOM based on a CSS-style selector. It can be as simple as accessing the child elements of a specific element,

      var sidebarPara = document.querySelectorAll(".sidebar p");
    

or as complex as selecting an element based on an attribute,

    var textInput = document.querySelectorAll("Input[type="text"]");

Similarly, it will also generate a nodeList, even if the selector matches only a single element.

  • Accessing an attribute value: getAttribute, as mentioned earlier, elements aren't the only things you can access with the DOM. To get the value of an attribute attached to an element node, we call getAttribute() with a single argument: the attribute name. For example, assuming that we have an imge, source.jpg, marked up like this,

      <img src="strad.jpg" alt="", id="lead-image">
    

In the following steps, we can access that specific image (getElementById) and save a reference to it in a variable. At that point, we could access any of the element's attribute (alt, src, or id) by specifying it as an argument in the getAttribute method.

    var bigImage = document.getElementById("lead-image");
    alert(bigImage.getAttribute("src")); // Alerts "strad.jpg".
Manipulating nodes

Once we've accessed a node using one of the methods discussed previously, the DOM gives us several built-in methods for manupulating those elements, their attributes and their contents.

setAttribute(), it sets the value of attribute which we acquired from the element. This method requires two arguments: the attribute to be changed and the new value for that attribute.

    var bigImage = document.getElementById("lead-image");
    bigImage.setAttribute("src", "lespaul.jpg");
  • What we can do with changing value of attributes?
    • update the checked attributes of checkboxes and radio buttons based on user interaction elsewhere on the page.
    • find the link element for our .css file and point the href value to a different style sheet, changing all the page's styles.
    • update a title attribute with information on an element's state ("this element is currently selected," for example.)

innerHTML gives us a simple method for accessing and changing the text and markup inside an element. For example, we need a quick way of adding a paragraph of text to the first element on our page with a class of intro,

    var introDiv = document.getElementByClassName("intro");
    introDiv.innerHTML = "<p>This is our intro text</p>";

style allows you to add, modify, or remove a CSS style from an element. The individual CSS properties are available as properties of the style property.

    document.getElementById("intro").style.color = "#fff";
    document.getElementById("intro").style.backgroundColor = "#f58220";
  • In JavaScript and the DOM, property names that are hyphenated in CSS (such as background-color and border-top-width) become camel case (backgroundColor, borderTopWidth, and so on) so the "-" character isn't mistaken for an operator.

  • the style property can also be used to get a style value for use elsewhere in the script. The following statement gets the background color of the #intro element and assigns it to the variable,

      var brandColor = document.getElementById("intro").style.backgroundColor;
    
Adding and removing elements

So far we've seen examples of getting and setting nodes in the existing document. The DOM also allows developers to change the document structure itself by adding and removing nodes on the fly. The methods shown below are more surgical and precise than adding content with innerHTML

createElement() creates a new element. This function accepts a single argument: the element to be created.

  • Once we create an element in this way, that new element remains floating in the JS ether until we add it to the document. Think of it as creating a reference to a new element that lives purely in memory -- something that we can manipulate in JS as we see fit, then add to the page once we're ready.

      var newDiv = document.createElement("div"); 
    

createTextNode() enters text into either an element we've created or an existing element on the page.

  • To use it, we provide a string of text as an argument, and the method creates a DOM-friendly version of that text, ready for inclusion on the page. Much like createElement, this creates a reference to the new text node that we can store in a variable and able to the page when the time comes.

      var outText = document.createTextNode("This is our text");
    

appendChild()

  • After creating a new element and a new string of text, we need to make them part of the document. This method takes a single argument: the node you want to add to the DOM. You call it on the existing element that will be its parent in the document structure. For example,

      // we have a single div on the page with the id="our-div""
      <div id="our-div"></div>
      // say we want to add a paragraph to #our-div that contains the text "Hello, world". We start by creating the p element (document.createElement()) as well as a text node for the content that will go inside it (createTextNode()).
      var ourDiv = document.getElementById("our-div");
      var newParagraph = document.createElement("p");
      var copy = document.createTextNode("Hello, World!");
      // now we have our element and some text, and we can use appendChild() to put the pieces together.
      newParagraph.appendChild(copy);
      ourDiv.appendChild(newParagraph);
      // the first statement appends copy (that's our "Hello World" text node) to the new paragraph we created (newParagraph), so now that element has some content. The second line appends the newParagraph to the original div (ourDiv). Now ourDiv isn't sitting there all empty in the DOM, and it will display on the page with the content "Hello, world."   
    

insertBefore() inserts an element before another element. It takes two arguments: the first is the node that gets inserted, and the second is the element it gets inserted in front of. You also need to know the parent to which the element will be added.

  • For example, to insert a new heading before the paragraph in this markup:

      <div id="our-div">
          <p id="our-paragraph">Our paragraph text</p>
      </div>
    
  • We start by assigning variable names to the div and the p it contains, then create the h1 element and its text node and put them together, just as we saw in the last example,

      var ourDiv = document.getElementById("out-div");
      var para = document.getElementById("our-paragraph");
    
      var newHeading = document.createElement("h1");
      var headingText = document.createTextNode("A new heading");
      newHeading.appendChild(headingText);
      // add our new text node to the new heading
    
  • Finally, in the last statement, the insertBefore() method places the newHeading h1 element before the para element inside ourDiv.

      ourDiv.insertBefore(newHeading, para);
    

replaceChild()

  • it replaces the one node with another and takes two arguments. The first argument is the new child (i.e., the node you want to end up with). The second is the node that gets replaced by the first. Like insertBefore(), you also need to identify the parent element in which the swap happens.

      <div id="our-div">
          <div id="swap-me"></div>
      </div>
    
  • and we want to replace the div with the id "swap-me" with an image. We start by creating a new img element and setting the src attribute to the path-name to the image file. In the final statement, we use replaceChild() to put newImg in place of swapMe.

      var ourDiv = document.getElementById("our-div");
      var swapMe = document.getElementById("swap-me");
      var newImg = document.createElement("img");
      // create a new image element 
    
      newImg.setAttribute("src", "path/to/image.jpg");
      // give the new image a "src" attribute
      ourDiv.replaceChild(newImg, swapMe);
    

removeChild()

  • it removes a node or an entire branch from the document tree. The method takes one argument, which is the node you want to remove. Remember that the DOM thinks in terms of nodes, not just elements, so the child of an element may be the text(node) it contains, not just other elements.

  • like appendChild, the removeChild method is always called on the parent element of the element to be removed (hence, "remove child"). That means we'll need a reference to both the parent node and the node we've looking to remove. For example,

      <div id="parent">
          <div id="remove-me">
              <p>Pssh, I never liked it here anyway.</p>
          </div>
      </div>
    
      // our script would look like this way
      var parentDiv = document.getElementById("parent");
      var removeMe = document.getElementById("remove-me");
      // removes the div with the id "remove-me" from the page.
      parentDiv.removeChild(removeMe);
    

JavaScript Libraries

Using JS, you don't have to write everything from scratch yourself. A JavaScrip library is a collection of prewritten functions and methods that you can use in your scripts to accomplish common tasks or simplify complex ones.

  • jQuery: It is free, open-source, and amploys a syntax that makes it easy to use if you are already handy with CSS, JS and the DOM.
  • Angular
  • REACT
  • Node.js And so on.
⚠️ **GitHub.com Fallback** ⚠️