Category Archives: 未分類

Mini Project

Evaluation

As one of the evaluations for your final grade, we will conduct a short exam. Please look at the about grading evaluation about further details. Please refer to the exam questions and answer sheets of 2011 .

Final Assignment(Mini Project)

For your final assignment, we encourage you to make a website in groups of 3-4 people.

We have already learned the basics of programming and how to use web services to some extent. By combining various Web services, you should have the skills to develop various programs. Let’s develop a program here with the intention of reviewing everything we have learned so far.

The program you create can be anything that uses JavaScript and Web services. You can make games, useful tools, information graphic sites, quizzes, instructions, blogs or anything else you wish to do. Please create a page that mentions that the project is a collaborative effort is done by everyone in the group.

Depending on the class, we may even allow you to work on the project independently. Please follow the instructions given to you by your teacher. Evaluation is done for each individual. When finalizing the presentation, please clarify who was in charge for what, and what percentage of work was done by each member.

When doing a project in a group, everyone must create a program. We do not evaluate things like “I took a picture”, “I wrote CSS” or “I created HTML”. We are judging you on your JavaScript ability so divide your JavaScript program into various functions and have one person write the code for each function.

Follow the instructions below to create.

  • The minimum requirement of the mini project is as follows.
    • Create a web page using JavaScript.
    • Use conditional branching.
    • Use loops.
  • Also please implement two or more from the following.
    • Use an array or a hash.
    • Use sensor information.
    • Use mashup.
    • Use library.

Themes and design

In order to develop software, we must first decide clearly what to make. First make a site mockup to decide roughly what site to make. It may be good to just design the web page in HTML first. Detailed specifications will be revealed once you do so. What HTML elements you use, what is displayed in the HTML elements, what happens when you enter characters in the text area, what happens when you press the button are all things that you will discover once you write the HTML.

If you clarify what happens when you type a letter in the text, what happens when you press the button, you will understand exactly what will happen. It is nothing but the design of the software structure. We will divide “what happens” into parts for each function and extract common parts that can be used. Let’s clarify what kind of web service you will use at this stage.

In order to develop a program as a team, the interface of each parts part must be clear. More specifically, clarify the data structure and function arguments. How do you express data in a program in a program? Is it passed by function call or global variable? What is the server side programming? It is also important to clarify what functions are doing. If you define that a function called add (x, y) is a function that adds the value of x and the value of y and returns the result, you do not mind seeing from the outside whatever its contents are implemented It is a translation.

In doing all this, you can clearly point to what part of the JavaScript program refers to a specific part in the HTML code. As a result, you will be able to decide who is responsible for what and where to proceed with the development clearly. If you are going to be responsible for the whole project, prepare the skeleton of the program proceed from there. For those who are supposed to be responsible for individual functions, develop the function, as well as develop a program that tests the function. In developing a larger program, it is usual for another person to be responsible for the development and testing of the program, but if it is on this scale, the number of people will be insufficient to do that, so developers = testers is good.

Program development

Using the script element

Basically, as described above, divide the software into parts parts, decide the developer for each part and develop the program for each part. The next question is how to combine the developed parts into one. In the case of JavaScript, you can load JavaScript programs prepared by others by using the script element. For this reason, you can prepare the JavaScript program as an independent file, and you can summarize it as a single software by loading it from the page that summarizes the whole.

What do you mean to prepare a JavaScript program as an independent page? In an information-based lesson, we created an HTML file that ends with .html under the public_html directory and created a Web page. In the same way, you can create a JavaScript program as an independent file using an editor and place it under public_html so that it can be read from other pages. Using this, we will be able to proceed independently with multiple people development.

For example, if a person with a login name of t00000aa puts a JavaScript program in a file called public_html / JS / sample.js, others can read the program as follows.

 

<script type="text/javascript" src="https://web.sfc.keio.ac.jp/~t00000aa/JS/sample.js"></script>

Final Report

On the final day of this class, we will hold a presentation where you will demonstrate your project in front of the rest of the class.

In the presentation, please explain not only the superficial things like what you made, but also the contents of the created program. Please use a flow chart for easier explanation.

In addition, evaluation is done for each individual, not for each group. Please explain exactly what each member was in charge of.

 

Mashup

Goals

One of the advantages of JavaScript is being able to incorporate modules developed by others into your own program in order to develop large-scale software that looks good. Today we will learn to use some of the services provided by others in our own programs.

  • Understand the concept of a mashup
  • Understand the mechanism of using services prepared by others.
  • Learn how to use web services like Google Maps, along with JSON and XML

Web Services

One of the reasons many universities prefer to teach JavaScript as a language is, that it is possible to utilize the services that people all over the world provide via the Web. A library is also one of these servoces, but the Web service is higher than the library in terms of processing on the server side and using data prepared on the server side. This time, we will explain mashups using Web service. Mashups are created to form new services by combining technology and contents from different providers. It is a technology that has attracted attention, and enables you to create large software systems in a very short time. In mashup, you do not need to know program details of the material service, you only need to pay attention to the procedure to call and the format of the data to be sent back, so it is better to create more complex services and data that you do not own you can realize the service you used.

The concept of Web services

As we have learned so far, JavaScript is mainly a language that operates on the browser. Therefore, if you can load JavaScript programs into your browser, you can run the program immediately. In other words, if you can load a function created by another person into the browser, you can use it freely. In the case of a mashup, the loaded program provides various services via the interface provided on the web server.

Webサービスの概念
Webサービスの概念

Using Web services

There are some necessary precautions to be taken while using Web services. Let us look at these in detail.

Programming

To use a Web service is just as simple as to access another site. For this reason, if you use a web service in an infinite loop, you will access a lot of other people’s sites at high speed. Even though the person who wrote the program does not have malicious intent, such an act seems to be a DoS attack (Denial of Service attack) from the viewpoint of the web service provider. When using Web services, please try to create programs with extreme caution so as not to disturb the side that provides Web services.

Security

When embedding other web services on your web page, you need to thoroughly examine their quality. If you embed the malicious web service of another person, you will be responsible for the wrong and may become an accomplice.

For example, if you easily use Web services created by unknown developers, there is a possibility that malicious actions such as leakage of personal information by the Web service may occur even if the service is convenient.

In order to avoid such situations, it is good to choose a web service that is safe enough that many people have used it for a long time.

Terms of Use

When using the Web service, it is necessary to check “terms of use” and adhere to it. For example, there are many cases where it is required to clearly indicate a provider, or to display a specific icon. In recent years, many services require user registration.

For example, it is necessary to pay particular attention,  when copying and using a part of the source of a friend’s home page. It may be necessary to copy not only the service call part but also the credit part, and since the URL will change, it may be necessary to register the user again. It is important to check the usage conditions on the home page of the target Web service provider.

XML and JSON

Many Web services can acquire data in XML format or JSON format. We will explain XML and JSON here.

XML

XML is Extensible Markup Language, it is a Markup Language like HTML. Like the HTML, it is being formulated by the World Wide Web Consortium (W3C). As its name implies, XML can extend elements by defining tags, so it is sometimes called a meta language. Basically, “<tag name>” indicates the beginning of the element, and “</ tag name>” indicates the end of the element. Currently, many formats such as XHTML and KML are developed based on XML.

JSON

XML has been made flexible, and a lot of data has been specified in this format. On the other hand, however, there are also many criticisms that file size becomes large and readability is bad. Therefore, a data description method called JSON (JavaScript Object Notation) that has good affinity with JavaScript was developed.

JSON is a data description method based on an object literal in JavaScript and is specified in RFC 4627. Basically, it follows the JavaScript object literal, but there are restrictions that the numerical value must be decimal notation. Also, the key of the object is supposed to be surrounded by “” in the character string. An example of data expressed in JSON is shown below. In this example, a line break is added for easy viewing, but it is not necessarily required.

{
    "name": {
        "familyName": "Keio",
        "firstName": "Taro"
    },
    "age": 19,
    "gender": "male"
}

Using Web Services: Google Maps

We will learn how to use Google Maps as an example of using Web service here.

Web Services

Complex Web services are provided in the world that we can freely use. When a function in a program created by the user calls another function (called an application program interface, API, etc.) provided by the web service, it communicates with the necessary server and provides a mechanism for using the service.

Webサービス実現の仕組み
Webサービス実現の仕組み

Let’s use a Web service that actually provides content.

Getting started with Google Maps

Below is a pasted version of Google Maps API provided by Google which you see often. Actually this program can be used easily.

The program demonstrated above is as follows. It may seem somewhat confusing compared to previous programs, but if you try it out yourself it is actually not that difficult.

HTML

&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;div id="map" style="width:300px;height:300px"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/div&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;callback=initMap" type="text/javascript"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;script type="text/javascript" src="mymap.js"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

JavaScript

function initMap() {
  // 地図の中心を決める
  var latlng = new google.maps.LatLng(35.388276, 139.427348);

  // 地図を表示するためのオプションを設定する
  var opt = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  // 地図を表示する。
  var map = new google.maps.Map(document.getElementById('map'), opt);
}

First, the first line of the HTML part secures an area for displaying the map using the div tag. Here, two attributes of id and style are specified, the ID is set to “map” by the id attribute, the size of the area is set to 300 px (pixel) in width and 300 px (pixel) in height by the style attribute .

The third line is reading the API for Google Maps. The Google Maps API  can be found at https://maps.googleapis.com/maps/api/js. So we need to load this program to use the Google Maps API. This line may be in the HTML header. In this case,  the API_KEY must be originally set. API_KEY can be obtained from Google ‘s key acquisition and authentication page. Currently, since the previous API did not require API_KEY, it seems to work without setting API_KEY in order to allow backward compatibility. In order to omit the API_KEY, delete the whole part related to API_KEY from : <script async defer src=”https://maps.googleapis.com/masps/api/api/js?key=YOUR_API_KEY&callback=initMap” type=”text/javascript”></script> so that it now looks like : “<script async defer src =” https://maps.googleapis.com/maps/api/js?callback=initMap “type =” text / javascript “> < / script> “.

Also, Google Maps API v3 has several options. Please see the Google Maps JavaScript API V3 Reference page for details.

The fourth line of the HTML part is a part that reads mymap.js which is a program file to be written by the user. Since we specified initMap () as a callback function when loading the Google Maps API, this program needs to include the initMap () function.

Let’s see the JavaScript program. First, in the third line, the center point of the map to be displayed is determined. We are making a new object with google.maps.LatLng (), but do not care too much about the details, we are just specifying the latitude and longitude as an argument and storing the result in a variable called latlng.

From the sixth line to the tenth line, parameters for actually displaying the map are set. Zoom is specified as 15 indicating the scale of the map. Likewise, the center indicates the center of the map is latlng, which is the variable generated earlie. The mapTypeId indicates the type of the map that is set in the road map (google.maps.MapTypeId.ROADMAP). These are all stored in the variable opt. Please note that opt ​​is an object.

The thirteenth line is finally for displaying the map. We use document.getElementById (‘map’) to specify where to display the map on the Web page, and display the map using the parameters set in opt.

For more detailed usage of the Google Maps API, please see the page and tutorial on the Google Maps JavaScript API V3 Reference, as above.

Setting up event listeners (callback functions) for Google Maps

When you display a map, you want to make some action when you can operate on the map. In order to realize this, Google Maps has the function for setting event listeners. An event listener is a callback function that is called when an event occurs.

See the next program. This shows an event listener added to the function for displaying the above map. On line 21, the event listener is set so that the click_callback () function is called for the click event. Also, the click_callback () function starting at line 16 is the body of the event listener. click_callback () has one dummy argument, and the state at the time of event occurrence is set in this variable. In this program, on the 17th line, latitude and longitude of the place where the event occurred, that is, the place where the event was clicked is displayed using alert ().

See the Google Maps JavaScript API V3 Reference page for information on what values ​​are returned in the arguments. Looking at the “click” in the Events table on this page, it says “Arguments: MouseEvent | IconMouseEvent”. This means that MouseEvent object or IconMouseEvent object is set and called. The IconMouseEvent object is a MouseEvent object plus an ID of a place called placeId. In fact, the arguments passed to the event listener called from the click event are IconMouseEvent when clicked on the normal map, and IconMouseEvent when the landmark is clicked.

function initMap() {
  // 地図の中心を決める
  var latlng = new google.maps.LatLng(35.388276, 139.427348);

  // 地図を表示するためのオプションを設定する
  var opt = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  // 地図を表示する。
  var map = new google.maps.Map(document.getElementById('map'), opt);

  // イベントリスナ(コールバック関数)
  function click_callback(e) {
    alert(e.latLng.toString());
  }

  // イベントリスナの設定
  map.addListener('click', click_callback);
}

Markers

By using the google.maps.Marker class you can set markers. See the next program. In this program, markers are created in line 16. On the 17th line, the location to place the marker is specified, and on the 18th line, the map where the marker is placed is specified. Setting an appropriate value for position allows you to set markers wherever you like.

function initMap() {
  // 地図の中心を決める
  var latlng = new google.maps.LatLng(35.388276, 139.427348);

  // 地図を表示するためのオプションを設定する
  var opt = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };

  // 地図を表示する。
  var map = new google.maps.Map(document.getElementById('map'), opt);

  // マーカーの追加
  var marker = new google.maps.Marker({
                     position: latlng,
                     map: map
		});
}

Markers also have various options, so please refer to MarkerOptions object specification.

Same origin policy as JSONP

Same generation policy

JavaScript has a restriction called the same generation policy, so that it cannot communicate with sites other than the site from which the JavaScript program was downloaded. This is the program that had been placed on the page that appears to communicate with other sites. It is a constraint on the information present in order to prevent leakage. Even the same content is judged to be from a different domain when accessing with http or https, so we must be careful.

However, the restriction that communication with the site other than the original site from which the program was downloaded is very severe. It could lead to lowering the convenience of JavaScript and is hence a double-edged sword.

Same source policy

From the JavaScript program, the same source policy can access only the site that brought the program. Conversely, if you have a JavaScript program for accessing the site you want to access, that is, the site with data, there will be no problem in accessing it. By utilizing this, it is possible to avoid the same-origin policy by preparing in advance and using a function to process the JSON, calling a function that is prepared from the site side that has the data.

For example, suppose you have the following program. Let’s assume that here the ninth line and thereafter are on different sites and will call the method with the data on that site as arguments. In this example, when the second line is executed, the function process () on line 10 is called. Then, from the function process (), func () which is a function defined by you is called with the data stored in the argument. By doing this, you can receive the data placed on another domain with the function you defined.

 

// 他のドメインにあるべき関数の呼び出し(読み込み)
process();

// 自分で定義した関数
function func(json) {
  alert(json.a + " + " + json.b + " = " + (json.a + json.b));
}

// 他のドメインにあるべき関数
function process() {
  func({ "a": 123, "b": 456 });
}

Actually it is used as follows. In this example, using the Query API of the MediaWiki API, the words beginning with “Keio” registered in WikiPedia are listed up and the top 50 is displayed. In the part of “<script src =” http://en.wikipedia.org/w/api.php?action=query&list=allpages&apfrom= Keio & aplimit = 50 & format = json & callback = func “>”, in fact it stated above a function with the data as arguments will be returned, so func () will be called. A function called from another program in this manner is called a callback function. Since how to pass the callback function depends on the Web service used, please refer to the Web service manual.

JavaScript

function func(json) {
  var ele = document.getElementById("listOfKeio");

  var i;
  for (i=0; i &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; json.query.allpages.length; i++) {
    ele.innerHTML += (i + ": " + json.query.allpages[i].title + "&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;br /&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;");
  }
}

HTML

&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;div id="listOfKeio"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/div&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;script src="myprog.js"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;script src="http://ja.wikipedia.org/w/api.php?action=query&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;list=allpages&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;apfrom=慶應&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;aplimit=50&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;format=json&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;callback=func"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

However, there are major problems in using this method to use the Web service. One can call the callback function only at the timing of accessing the Web service page, that is, the Wikipedia page with the script element. With this, it is impossible to retrieve data at the necessary timing.

Therefore, when using JSONP, generate a script element in the program as follows. In the twelfth line of the JavaScript part, a script element is newly generated and assigned to the variable o. createElement () is a method for creating a new HTML element. In line 13, the src attribute is added to the script element generated in the 12th line using the setAttribute () method. After that, in the 14th line, the generated script element is set as a child of the div element, that is, within the div element. As a result, the callback function func () is called at the timing when the script element is displayed (in fact it is not visible to the eyes but embedded in the HTML document), that is, when the button is pressed.

 

HTML部

&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;script type="text/javascript" src="myprog.js"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/script&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;button id="listKeio" onclick="getFromWikipedia()"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;List&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/button&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;div id="listOfKeio"&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;/div&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

JavaScript部

function func(json) {
  var ele = document.getElementById('listOfKeio');

  var i;
  for (i=0; i &amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt; json.query.allpages.length; i++) {
    ele.innerHTML += i + ": " + json.query.allpages[i].title + "&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;br /&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;";
  }
}

function getFromWikipedia() {
  var e = document.getElementById('listOfKeio');
  var o = document.createElement("script");
      o.setAttribute("src", "http://ja.wikipedia.org/w/api.php?action=query&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;list=allpages&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;apfrom=慶應&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;aplimit=50&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;format=json&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;callback=func");
  e.appendChild(o);
}

Exercise 11-

Please refer to the above description and create a program to display Google Map.

Exercise 11-

Based on the above explanation, display Google Map and click on the map, create a program showing the latitude and longitude of that place.

Note: You can not call https://maps.googleapis.com/maps/api/js more than once on the same page. Therefore, when creating on the same page as other exercises, care must be taken because it is necessary to combine callback functions into one.

Exercise 11-

Based on the above explanation, display Google Map and click on the map so that a map centered on that place is displayed. To change the center point of the map, use the setCenter () method of the map object. For example, if the map object is in the variable map, set it like map.setCenter (lonlat). Here, lonlat is an object containing latitude and longitude.

Note: You can not call https://maps.googleapis.com/maps/api/js more than once on the same page. Therefore, when creating on the same page as other exercises, care must be taken because it is necessary to combine callback functions into one.

Exercise 11-

Based on the above explanation, please display a Google Map and click on the map, create a program that will place a marker in that place. Also, at that time, make sure the markers are labeled “1”, “2”, “3”. Please note that the value of the label property when generating the Marker object must be a string.

Note: You can not call https://maps.googleapis.com/maps/api/js more than once on the same page. Therefore, when creating on the same page as other exercises, care must be taken because it is necessary to combine callback functions into one.

Exercise 11-

With reference to the explanation above, please create a program that displays 50 words related to Kei by pressing a button.

Libraries

Goals

One of the real thrills of JavaScript is being able to incorporate modules developed by others into your program and to develop large-scale software that looks good. Today you will learn to use the libraries provided by others and incorporate them into your programs.

  • Understand the concept of libraries.
  • Understand the mechanism of using libraries prepared by others.
  • Using libraries like jQuery.

JQuery

jQuery Basics

What is jQuery?

The basis of JavaScript is to give movement to pages written in HTML. You can use it to add an action by pressing a button or change the contents displayed on the page according to the value entered in the form. However, the more you try to do something complicated, the more troublesome procedures will come up. Therefore, in order to make JavaScript easier to use, libraries have been developed. A library is a package of reusable versatile functions packaged together.

In JavaScript, many people develop and publish various libraries. Here, we will introduce jQuery which is often used among them.

jQuery is a JavaScript library developed and released in 2006, which is characterized by adopting a description method similar to CSS. Using jQuery makes it possible to manipulate HTML with shorter code.

 

How to use jQuery

To use jQuery, you need to download the jQuery library from the jQuery site, place it on your site and read it using the script element. On jQuery’s site, a compressed library called Minified and a pre-compression library called Uncompressed are provided. These two functions are the same, but we usually use Minified. This is because the file size is kept small using techniques such as shortening variable names and omitting comments, so that the downloading ends quickly. On the other hand, the Minified library is not suitable for human reading, and if you are interested in the jQuery code itself, you should download the Uncompressed library.

We normally download the jquery library and host it on this server, but in this lesson we will use the Minified library at https://ipl.sfc.keio.ac.jp/text/info2-2017-9/lib/jquery-3.2.1.min.js Since the Uncompressed library is located at https://ipl.sfc.keio.ac.jp/text/info2-2017-9/lib/jquery-3.2.1.js in -3.2.1.min.js. If you click on each link and display it, you can see the difference between the Minified library and the Uncompressed library.

Getting started with jQuery

Let’s try using jQuery. Look at the next program.




<ul>
 	


<li>Hello World!</li>



 	


<li class="ex">Hello SFC!</li>



</ul>



 
$(function(){
  $("li.ex").css("color", "red");
});

Output

  • Hello World!
  • Hello SFC!

In the program, we read https://ipl.sfc.keio.ac.jp/text/info2-2017-9/lib/jquery-3.2.1.min.js with the first script element. Also, the second script element is completely different from the JavaScript that we have learned so far. The second script element is a program using jQuery.

In jQuery, it is basically a matter of designating which part of HTML is to be manipulated, and then writing which contents to manipulate. Those that designate the part to be operated are called selectors. It is the same as the CSS selector. In the above program, the portion of “li” surrounded by “$ (…)” on line 9 is the selector. In this example all li elements are specified. You can also specify classes, IDs etc in the same as you do in CSS. If the operation part of jQuery is “css (” color “,” red “)”, it specifies the color of the character as red. As a result, all the bullets are displayed in red.

What is “$ (function () {” in the 8th line and “})” in the 10th line? “This is the part that specifies the timing when the jQuery command is executed. To be exact, it is “$ (document) .ready (function () {” and “});”, but “$ (function () {” and “});” is used as an abbreviation. It is understood by looking at the non-abbreviated form, but this description method indicates that it is executed when the document is ready. That is, when loading the page is completed, its contents (“$ (” li “). Css (” color “,” red “);” in this program are executed. In many cases, since you want to start processing after all HTML has been loaded, the program is often written in the part surrounded by “$ (function () {” and “});”.


<script type="text/javascript" src="https://ipl.sfc.keio.ac.jp/text/info2-2017-9/lib/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
  jQuery program
});
</script>

In many cases we mentioned that the program is written in the part surrounded by "$ (function () {" and "})" ", but this is not the case when program is run in an event-driven manner. For example, see the following program. This may make more sense syntactically.

<div id="helloworld">Hello World!</div>
<button onclick="changeColor()">Click me!</button>

<script type="text/javascript" src="https://ipl.sfc.keio.ac.jp/text/info2-2017-9/lib/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function changeColor() {
  $("#helloworld").css("color", "red");
}
</script>

The result of executing this program is as follows. Please press the button. The color of the part indicated as "Hello World!" Probably changed. That is, by using jQuery, operations that we have done using getElementById () etc. are described shortly and easily.

Hello World!

Here "#helloworld" we use as a selector in jQuery. In jQuery, if you add "#" before the character string, it refers to the id attribute. If you do not add anything, it simply refers to the element, and if you add "#", it refers to the id attribute. As mentioned earlier, this is the same as for CSS's selector.

Selectors

As shown above, in order to use jQuery, it is necessary to master the selection. Let's take a closer look at how to specify selectors here.

Element Selectors

The element selector is a selector for designating a specific element as described above. If there are multiple specified elements, all of them are eligible. This method is easy, as one simply refers to the element by its name.

ID Selectors

The ID selector is for specifying the id attribute attached to the element. Since there is no element with the same id attribute on one page, using this specification method, it is possible to specify only one specific element. For the description method, prefix "id" attribute name with "#". You can also write an element selector and an ID selector like "$ (" div # helloworld ")". Here, "div" is the element name, and "helloworld" is the value of the id attribute.

Class Selectors

The class selector is for specifying the class attribute attached to the element. If there are multiple specified classes, all of them are eligible. In order to select, add "." before the class attribute name. You can also write an element selector and an ID selector like "$ (" div.article ")". Here, "div" is the element name and "article" is the value of the class attribute.

Descendant Selectors

The descendant selector is for narrowing down the elements that are further inside the element. For example, there is a sentence "descendant selector is for designating descendants" and is used when specifying a strong element in a div element, that is, "descendant selector" portion. To select, parent elements and descendant elements are written contiguously, separated by spaces. For example, "$ (" div strong ")". It does not necessarily need to be an element name, it is also possible to specify it using "$ (". Article strong ")".

Universal Selectors

The universal selector is for selecting all elements. To specify the universal selector, use "* (asterisk)". For example, to specify all the elements in a div element, write it like "$ (" div * ")".

Multiple Selectors (or)

It is a type designation method that matches with multiple selectors. To specify multiple selectors in parallel, separate them with ",". For example, "$ (" # question1, # question2 ")" is specified.

Multiple Selectors (and)

It is a method of specifying what matches all of the plurality of selectors. Multiple selectors are arranged without dividing. For example, in the case of a class, specify "$ (". Class1.class2 ")". It is easy to specify by using "+" as "$ (". Class1 "+". Class 2 ")".

Other Selectors

In addition to the ones introduced above, jQuery has various selectors. For more details please refer to the jQuery document selector documentation.




<ul>
 	


<li id="campus1" class="tokyo">Shinanomachi</li>



 	


<li id="campus2" class="tokyo">Shiba Kyoritsu</li>



 	


<li id="campus3" class="kanagawa">Shonan Fujisawa</li>



 	


<li id="campus4" class="kanagawa">Hiyoshi</li>



 	


<li id="campus5" class="tokyo">Mita</li>



 	


<li id="campus6" class="kanagawa">Yagami</li>



</ul>




function reset() {
  $("li").css("color", "black");
}
function tokyo() {
  $(".tokyo").css("color", "red");
}
function kanagawa() {
  $(".kanagawa").css("color", "red");
}
function campus1() {
  $("#campus1").css("color", "red");
}
function campus2() {
  $("#campus2").css("color", "red");
}
function campus3() {
  $("#campus3").css("color", "red");
}
function campus4() {
  $("#campus4").css("color", "red");
}
function campus5() {
  $("#campus5").css("color", "red");
}
function campus6() {
  $("#campus6").css("color", "red");
}
  • Shinanomachi
  • Shiba Kyoritsu
  • Shonan Fujisawa
  • Hiyoshi
  • Mita
  • Yagami

Manipulating documents with jQuery

By using jQuery, you can manipulate the HTML and CSS that make up the document. Here, the operation of the document will be described.

CSS control

As we saw in the previous chapter, you can dynamically manipulate CSS by using jQuery. Use css () to operate CSS. The format of css () is "css (property name, value)". Here, the property name is a property name such as "" color "" or "" background-color "" and the value is a character string of the value to be set for that property.

It is also possible to change multiple properties simultaneously. For example, to change the color of the text and the background color at the same time, do as shown below. The property name is different from that of CSS, and it is a property name used when specifying CSS with JavaScript. In other words, if the property name of the CSS is connected with "-" like "background-color", delete "-" , then capitalize the next letter.

 
$("div").css({
  backgroundColor: "red",
  color: "blue"
});

In a program, you may want to know the value of a CSS property. In this case also use css (). However, the format is different from when setting the property, and it becomes "css (property name)".




<div id="weather">Sunny</div>


<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22javascript%22%20src%3D%22ipl.sfc.keio.ac.jp%252Ftext%252Finfo2-2017-9%252Flib%252Fjquery-3.2.1.min.js%22%3E%3C%2Fscript%20%2F%3E%0A%5B%2Fcode%5D%3C%2Fpre%3E%0A%3Cp%3E%3Cspan%20id%3D%22result_box%22%20class%3D%22%22%20lang%3D%22en%22%20tabindex%3D%22-1%22%3EFor%20example%2C%20executing%20the%20above%20program%20results%20in%20the%20following%20result.%20Here%2C%20the%20color%20is%20%22rgb%20(51%2C%2051%2C%2051)%22.%20Actually%2C%20the%20colors%20displayed%20by%20the%20CSS%20specified%20on%20the%20page%20are%20different.%20Each%20value%20indicates%20red%2C%20green%2C%20blue%2C%20and%20takes%20a%20value%20from%200%20to%20255.%3C%2Fspan%3E%3C%2Fp%3E%0A%3Cp%3E%3Cimg%20class%3D%22alignnone%20size-full%20wp-image-757%22%20src%3D%22https%3A%2F%2Fipl.sfc.keio.ac.jp%2Ftext%2Finfo2-2017-9%2Fwp-content%2Fuploads%2F2017%2F08%2F9b8ba325833c44002b1917c1987c2fa0.png%22%20alt%3D%22%22%20width%3D%22616%22%20height%3D%22414%22%20%2F%3E%3C%2Fp%3E%0A%3Ch4%3EHTML%20operation%3C%2Fh4%3E%0A%3Cp%3E%3Cspan%20id%3D%22result_box%22%20class%3D%22%22%20lang%3D%22en%22%20tabindex%3D%22-1%22%3ESo%20far%20we%20have%20rewritten%20the%20contents%20of%20HTML%20elements%20using%20innerHTML%20().%20jQuery%20also%20provides%20the%20same%20function.%20In%20order%20to%20rewrite%20contents%20of%20HTML%20elements%20with%20jQuery%2C%20use%20%22html%20()%22.%20The%20method%20of%20use%20is%20simple%2C%20and%20it%20is%20as%20follows.%3C%2Fspan%3E%3C%2Fp%3E%0A%3Cp%3E%3Cspan%20id%3D%22result_box%22%20class%3D%22%22%20lang%3D%22en%22%20tabindex%3D%22-1%22%3EIn%20this%20example%2C%20the%20portion%20that%20was%20originally%20supposed%20to%20be%20displayed%20as%20%22sunny%22%20by%20HTML%20is%20replaced%20with%20%22cloudy%20rain%20sometimes.%22%3C%2Fspan%3E%3C%2Fp%3E%0A%3Cp%3E%3Cspan%20id%3D%22result_box%22%20class%3D%22%22%20lang%3D%22en%22%20tabindex%3D%22-1%22%3EEven%20by%20using%20html%20()%2C%20you%20can%20get%20the%20value.%20By%20sending%20an%20empty%20argument%20you%20can%20get%20the%20HTML%20code%20of%20an%20element.%3C%2Fspan%3E%3C%2Fp%3E%0A%3Ch4%3EInserting%20and%20moving%20HTML%20elements%3C%2Fh4%3E%0A%3Cp%3E%3Cspan%20id%3D%22result_box%22%20class%3D%22%22%20lang%3D%22en%22%20tabindex%3D%22-1%22%3E%3Cspan%20title%3D%22jQuery%E3%82%92%E4%BD%BF%E3%81%86%E3%81%93%E3%81%A8%E3%81%AB%E3%82%88%E3%81%A3%E3%81%A6%E3%80%81HTML%E8%A6%81%E7%B4%A0%E3%81%AE%E6%8C%BF%E5%85%A5%E3%82%84%E7%A7%BB%E5%8B%95%E3%82%92%E8%A1%8C%E3%81%86%E3%81%93%E3%81%A8%E3%81%8C%E3%81%A7%E3%81%8D%E3%82%8B%E3%80%82%22%3EBy%20using%20jQuery%2C%20HTML%20elements%20can%20be%20inserted%20and%20moved.%20%3C%2Fspan%3E%3Cspan%20title%3D%22%E4%B8%8B%E8%A8%98%E3%81%AE%E8%A1%A8%E3%81%AB%E3%81%BE%E3%81%A8%E3%82%81%E3%82%8B%E3%80%82%20%22%3EIt%20is%20summarized%20in%20the%20table%20below.%3C%2Fspan%3E%3C%2Fspan%3E%3C%2Fp%3E%0A%3Cp%3E%3Cspan%20title%3D%22%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E3%81%AF%E3%80%81sel1%20%E3%82%92%E5%80%A4%E3%81%A8%E3%81%97%E3%81%A6%E8%BF%94%E3%81%99%E3%80%82%22%3EThe%20method%20returns%20sel%201%20as%20a%20value.%20%3C%2Fspan%3E%3Cspan%20title%3D%22%E4%B8%8A%E8%A8%98%E3%81%A7%E3%80%81sel2%20%E3%81%AE%E3%81%A8%E3%81%93%E3%82%8D%E3%81%AB%20%24(%26quot%3B%26lt%3Bdiv%26gt%3B1%26lt%3B%2Fdiv%26gt%3B%26quot%3B)%20%E3%81%BE%E3%81%9F%E3%81%AF%E3%80%81%26quot%3B%26lt%3Bdiv%26gt%3B1%26lt%3B%2Fdiv%26gt%3B%26quot%3B%20%E3%81%AA%E3%81%A9%E3%81%AE%E3%82%88%E3%81%86%E3%81%AB%E3%80%81html%20%E3%82%92%E6%9B%B8%E3%81%8F%E3%81%93%E3%81%A8%E3%82%82%E3%81%A7%E3%81%8D%E3%82%8B%E3%80%82%22%3EYou%20can%20also%20write%20html%20like%20%24%20(%22%26lt%3Bdiv%26gt%3B%201%20%26lt%3B%2F%20div%26gt%3B%22)%20or%20%22%26lt%3Bdiv%26gt%3B%201%20%26lt%3B%2F%20div%26gt%3B%22%20at%20sel%202%20above.%20%3C%2Fspan%3E%3Cspan%20title%3D%22%EF%BC%88html%20%E3%82%92%E6%9B%B8%E3%81%8F%E5%A0%B4%E5%90%88%E3%81%AF%E3%80%81%E6%96%B0%E8%A6%8F%E7%94%9F%E6%88%90%EF%BC%8B%E7%A7%BB%E5%8B%95%E3%81%AA%E3%81%AE%E3%81%A7%E3%80%81%E6%8C%BF%E5%85%A5%E3%81%A8%E3%81%84%E3%81%86%E3%82%A4%E3%83%A1%E3%83%BC%E3%82%B8%E3%81%AB%E3%81%AA%E3%82%8B%EF%BC%89%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E3%81%AF%E3%80%81%E7%A7%BB%E5%8B%95%E5%BE%8C%E3%81%AE%E8%A6%81%E7%B4%A0%E3%82%92%E5%80%A4%E3%81%A8%E3%81%97%E3%81%A6%E8%BF%94%E3%81%99%E3%80%82%22%3E(When%20writing%20html%2C%20since%20it%20is%20a%20new%20element%20%2B%20movement%2C%20we%20insert%20elements)%20This%20method%20returns%20the%20element%20after%20we%20move%2Finsert%20it.%20%3C%2Fspan%3E%3Cspan%20title%3D%22%E4%B8%8A%E8%A8%98%E3%81%A7%E3%80%81sel2%20%E3%81%AE%E3%81%A8%E3%81%93%E3%82%8D%E3%81%AB%E3%80%81%24(%26quot%3B%26lt%3Bdiv%26gt%3B1%26lt%3B%2Fdiv%26gt%3B%26quot%3B)%20%E3%81%AA%E3%81%A9%E3%81%AE%E3%82%88%E3%81%86%E3%81%AB%E3%80%81html%20%E3%82%92%E6%9B%B8%E3%81%8F%E3%81%93%E3%81%A8%E3%82%82%E3%81%A7%E3%81%8D%E3%82%8B%E3%80%82%22%3EIn%20the%20above%2C%20you%20can%20also%20write%20html%20like%20sel2%2C%20like%20%24%20(%22%26lt%3Bdiv%26gt%3B%201%20%26lt%3B%2F%20div%26gt%3B%22).%20%3C%2Fspan%3E%3Cspan%20title%3D%22%EF%BC%88html%20%E3%82%92%E6%9B%B8%E3%81%8F%E5%A0%B4%E5%90%88%E3%81%AF%E3%80%81%E6%96%B0%E8%A6%8F%E7%94%9F%E6%88%90%EF%BC%8B%E7%A7%BB%E5%8B%95%E3%81%AA%E3%81%AE%E3%81%A7%E3%80%81%E6%8C%BF%E5%85%A5%E3%81%A8%E3%81%84%E3%81%86%E3%82%A4%E3%83%A1%E3%83%BC%E3%82%B8%E3%81%AB%E3%81%AA%E3%82%8B%EF%BC%89%E3%82%88%E3%82%8A%E8%A9%B3%E3%81%97%E3%81%8F%E3%81%AFjQuery%E3%81%AE%E3%83%89%E3%82%AD%E3%83%A5%E3%83%A1%E3%83%B3%E3%83%88%E3%81%AE%E6%93%8D%E4%BD%9C%E3%81%AE%E7%AB%A0%E3%82%92%E5%8F%82%E7%85%A7%E3%81%97%E3%81%A6%E3%81%BB%E3%81%97%E3%81%84%E3%80%82%22%3E(When%20writing%20html%2C%20it%20is%20a%20virtual%20insertion%20as%20it%20is%20newly%20created%20%2B%20moved)%20For%20more%20details%2C%20see%20the%20%3Ca%20href%3D%22http%3A%2F%2Fapi.jquery.com%2Fcategory%2Fmanipulation%2F%22%3Echapter%20on%20manipulating%20jQuery's%20documentation%3C%2Fa%3E.%20%3C%2Fspan%3E%3C%2Fp%3E%0A%3Cp%3E%3Cspan%20id%3D%22result_box%22%20class%3D%22%22%20lang%3D%22en%22%20tabindex%3D%22-1%22%3E%3Cspan%20title%3D%22%E4%BB%96%E3%81%AB%E3%82%82%E6%B2%A2%E5%B1%B1%E3%81%AE%E6%93%8D%E4%BD%9C%E3%81%AE%E3%81%9F%E3%82%81%E3%81%AE%E3%83%A1%E3%82%BD%E3%83%83%E3%83%89%E3%81%8C%E7%94%A8%E6%84%8F%E3%81%95%E3%82%8C%E3%81%A6%E3%81%84%E3%82%8B%E3%80%82%22%3EThere%20are%20many%20other%20methods%20for%20doing%20this.%20%3C%2Fspan%3E%3Cspan%20title%3D%22%E3%83%95%E3%82%A9%E3%83%BC%E3%83%A0%E3%81%8B%E3%82%89%E3%81%AE%E5%80%A4%E3%81%AE%E5%8F%96%E5%BE%97%E3%81%93%E3%82%8C%E3%81%BE%E3%81%A7%E3%81%AE%E3%83%97%E3%83%AD%E3%82%B0%E3%83%A9%E3%83%A0%E3%81%A7%E3%81%AF%E3%80%81%E3%83%95%E3%82%A9%E3%83%BC%E3%83%A0%E3%80%81%E7%89%B9%E3%81%AB%E3%83%86%E3%82%AD%E3%82%B9%E3%83%88%E3%82%A8%E3%83%AA%E3%82%A2%E3%81%8B%E3%82%89%E3%81%AE%E5%80%A4%E3%81%AE%E5%85%A5%E5%8A%9B%E3%82%92%E5%A4%9A%E7%94%A8%E3%81%97%E3%81%A6%E3%81%8D%E3%81%9F%E3%80%82%22%3EAcquiring%20a%20value%20from%20past%20programs%2C%20we%20frequently%20use%20the%20input%20of%20values%20%E2%80%8B%E2%80%8Bfrom%20forms%2C%20especially%20text%20areas.%20j%3C%2Fspan%3E%3Cspan%20title%3D%22%E3%81%93%E3%81%AE%E3%82%88%E3%81%86%E3%81%AA%E5%80%A4%E3%81%AE%E5%85%A5%E5%8A%9B%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6%E3%82%82jQuery%E3%81%AF%E7%B0%A1%E5%8D%98%E3%81%AA%E3%82%A4%E3%83%B3%E3%82%BF%E3%83%BC%E3%83%95%E3%82%A7%E3%82%A4%E3%82%B9%E3%82%92%E6%8F%90%E4%BE%9B%E3%81%97%E3%81%A6%E3%81%84%E3%82%8B%E3%80%82%22%3EQuery%20also%20provides%20a%20simple%20interface%20for%20entering%20such%20values.%20%3C%2Fspan%3E%3Cspan%20title%3D%22%E4%BE%8B%E3%81%88%E3%81%B0%E3%80%81%E4%B8%8B%E8%A8%98%E3%81%AF%E5%88%9D%E6%9C%9F%E3%81%AE%E9%A0%83%E3%81%AB%E4%BD%BF%E3%81%A3%E3%81%9F%E4%BE%8B%E3%81%A7%E3%80%81%E5%90%8D%E5%89%8D%E3%82%92%E5%85%A5%E5%8A%9B%E3%81%99%E3%82%8B%E3%81%A8%E3%80%8C%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF%E2%97%8B%E2%97%8B%E3%81%95%E3%82%93%E3%80%8D%E3%81%A8%E8%A1%A8%E7%A4%BA%E3%81%95%E3%82%8C%E3%81%9F%E3%82%A2%E3%83%A9%E3%83%BC%E3%83%88%E3%81%8C%E5%87%BA%E3%82%8B%E3%81%A8%E3%81%84%E3%81%86%E3%82%82%E3%81%AE%E3%81%A7%E3%81%82%E3%82%8B%E3%80%82%22%3EFor%20example%2C%20the%20following%20is%20an%20example%20used%20in%20the%20early%20days%2C%20when%20an%20input%20of%20a%20name%20is%20entered%2C%20an%20alert%20indicating%20%22Hello%20Mr.%20%E2%97%8B%20%E2%97%8B%22%20appears.%3C%2Fspan%3E%3C%2Fspan%3E%3C%2Fp%3E%0A%3Cp%3E%26nbsp%3B%3C%2Fp%3E%0A%3Cpre%3E%5Bcode%20language%3D%22html%22%5D%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0Afunction%20hello()%7B%20%2F%2F%20Text%20Element%0A%20var%20name%20%3D%20document.getElementById(%22text1%22)%3B%20%2F%2FAlert%20alert(%22Hello%E3%80%81%22%20%2B%20name.value)%3B%20%7D%20%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />

<form> Your Name:<input id="text1" type="text" size="20"><input type="button" value="OK" onclick="hello()"></form>


When this is rewritten using jQuery, it becomes as follows. By using "val ()" it is easy to get the value of the input element.

 <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%20src%3D%22https%3A%2F%2Fipl.sfc.keio.ac.jp%2Ftext%2Finfo2-2017-9%2Flib%2Fjquery-3.2.1.min.js%22%3E%3Cscript%20type%3D%22text%2Fjavascript%22%3E%20%0A%0A%3C%2Fp%3E%0A%3Cform%3E%20Your%20Name%3A%20%3Cinput%20id%3D%22text1%22%20type%3D%22text%22%20size%3D%2220%22%3E%3Cinput%20type%3D%22button%22%20value%3D%22OK%22%20onclick%3D%22hello()%22%3E%3C%2Fform%3E%0A%3Cp%3E%20%0A%5B%2Fcode%5D%3C%2Fpre%3E%0A%3Cpre%3E%5Bcode%20language%3D%22javascript%22%5D%0Afunction%20hello()%7B%20%2F%2F%20Alert%0A%20alert(%22Hello%2C%22%20%2B%20%24(%22input%23text1%22).val())%3B%0A%20%7D%0A%5B%2Fcode%5D%3C%2Fpre%3E%0A%3Cp%3E%3Cspan%20id%3D%22result_box%22%20class%3D%22%22%20lang%3D%22en%22%20tabindex%3D%22-1%22%3EYou%20can%20also%20use%20val%20()%20to%20set%20the%20value.%20When%20setting%20a%20value%2C%20write%20%22val%20(value)%22.%20For%20example%2C%20do%20as%20follows.%3C%2Fspan%3E%3C%2Fp%3E%0A%3Cpre%3E%5Bcode%20language%3D%22javascript%22%5D%20%24(%22input%23text1%22).val(%22Sato%22)%3B%20%5B%2Fcode%5D%3C%2Fpre%3E%0A%3Ch2%3EMethod%20Chain%3C%2Fh2%3E%0A%3Cp%3E%3Cspan%20id%3D%22result_box%22%20class%3D%22%22%20lang%3D%22en%22%20tabindex%3D%22-1%22%3E%3C%2Fspan%3E%3Cspan%20id%3D%22result_box%22%20class%3D%22%22%20lang%3D%22en%22%20tabindex%3D%22-1%22%3EIf%20you%20want%20to%20apply%20multiple%20methods%20to%20an%20element%20in%20turn%2C%20jQuery%20provides%20an%20interface%20called%20method%20chain.%20For%20example%2C%20if%20you%20want%20to%20perform%20three%20operations%20on%20one%20element%20as%20shown%20below%20do%20the%20following.%3Cbr%20%2F%3E%0A%3C%2Fspan%3E%3C%2Fp%3E%0A%3Cpre%3E%5Bcode%20language%3D%22javascript%22%5D%20%3C%2Fp%3E%0A%3Cdiv%20id%3D%22soup%22%3E%3C%2Fdiv%3E%0A%3Cp%3E%0A%3Cscript%20type%3D%22text%2Fjavascript%22%20src%3D%22https%3A%2F%2Fipl.sfc.keio.ac.jp%2Ftext%2Finfo2-2017-9%2Flib%2Fjquery-3.2.1.min.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" /><img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0A%24(%22div%23soup%22).prepend(%22%E5%BE%A1%22)%3B%20%24(%22div%23soup%22).prepend(%22%E5%BE%A1%22)%3B%20%24(%22div%23soup%22).prepend(%22%E3%81%8A%22)%3B%20%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" />

In this case, three operations can be written as follows.

 

<div id="soup">付け</div>


<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%20src%3D%22https%3A%2F%2Fipl.sfc.keio.ac.jp%2Ftext%2Finfo2-2017-9%2Flib%2Fjquery-3.2.1.min.js%22%3E%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" /><img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%3E%20%24(%22div%23soup%22).prepend(%22%E5%BE%A1%22).prepend(%22%E5%BE%A1%22).prepend(%22%E3%81%8A%22)%3B%20%3C%2Fscript%3E" data-mce-resize="false" data-mce-placeholder="1" class="mce-object" width="20" height="20" alt="&lt;script&gt;" title="&lt;script&gt;" /> 

Of course, it does not matter if different methods are mixed. Event model by jQuery also provides an interface of its own. Here, we explain the method of event handling using jQuery.

At the very beginning, we explained that jQuery's program is often written between "$ (function () {" and "});" However, until now, almost no such example has appeared. Here, we will explain in greater detail the meaning of "$ (function () {" and "});".

"$ (Function () {" ~ "});" is an abbreviation of "$ (document) .ready (function () {" ~ "));" as mentioned earlier. So what is "$ (document) .ready (function () {" ~ "));" In jQuery usage, it has taken the form of "element selection method. However, in fact jQuery can define events outside it. This identity of "$ (document) .ready (function () {" ~ "));" "$ (Document) .ready (function () {" ~ "));" is executed in the event that "$ (document)", that is, "ready ()" for the entire document is there.

Since the "ready ()" event occurs when the entire document is read, "$ (document) .ready (function () {" ~ "});" is the state in which all the pages are displayed as a conclusion. It is executed immediately after. In other words, you can use "$ (document) .ready (function () {" ~ "});" to execute the program after loading the page rather than before.

click () and the basics of event handling

Now that we can understand the interesting things in " (document) .ready (function () {" ~ "));" let's look at another event. First of all, the most basic event, click (). As you can see, click () is for handling events that occur when an element is clicked.

Look at the next program. In this program, one button is made in the HTML part of the first line. However, we do not use functions with onclick attribute as before. Instead, the JavaScript program uses jQuery to define event handlers with "$ (" button "). Click (function () {" ~ "}); "$ (" Button "). Click ()" means that a click event occurs in the button element. When a click event occurs, the inside of the function, that is, the part enclosed in curly brackets is executed.

 
<script type="text/javascript" src="https://ipl.sfc.keio.ac.jp/text/info2-2017-9/lib/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function() {
  $("button").click(function(){
    alert("Click!!");
  });
});
</script>

<button>Click me</button>

Exercise 10-

With jQuery, create a button to change the background color of elements containing ccc, including aaa and bbb, to the color you entered in the input area. Use the following HTML. However, when you press the button, first return to the initial state.

<p class="aaa">Element1</p>
<p class="aaa bbb">Element2</p>
<p class="ccc aaa bbb">Element3</p>
<p class="aaa ccc bbb">Element4</p>
<p class="aaa bbb">Elementy5</p>
function reset101() {
    var ele = document.getElementsByClassName("element");
    for (var i=0; i<ele.length; i++) {
        ele[i].style.backgroundColor = "transparent";
    }
}
function exccc() {
    reset101();
    var ele = document.getElementsByClassName("exccc");
    var col = document.getElementById("colortext");

    for (var i=0; i<ele.length; i++) {
        ele[i].style.backgroundColor = col.value;
    }
}
function exaaabbb() {
    reset101();
    var ele = document.getElementsByClassName("exaaa exbbb");
    var col = document.getElementById("colortext");

    for (var i=0; i<ele.length; i++) {
        ele[i].style.backgroundColor = col.value;
    }
}

Element 1

Element 2

Element 3

Element 4

Element 5

Exercise 10-

Create a gambling game as follows using jQuery.

0 th person

Method Explanation
sel1.prepend(sel2) Move the element specified by sel 2 to the beginning of the element specified by sel 1.
sel1.append(sel2) Move the element specified by sel 2 to the end of the element specified by sel 1.
sel1.before(sel2) Move the element specified by sel 2 immediately before the element specified by sel 1.
sel1.after(sel2) Move the element specified by sel 2 immediately after the element specified by sel 1.
Method Explanation
prependTo(sel) Move an element specifying a method to the beginning of the element selected by the selector specified by sel.
appendTo(sel) Move an element that specifies a method to the end of the element selected by the selector specified by sel.
insertBefore(sel) Move the element with the method specified before the element selected by the selector specified by sel.
insertAfter(sel) Move the specified element after the element selected by the selector specified by sel
Method Explanation
click() The element is clicked with the mouse.
dblclick() The element is double clicked with the mouse.
mousedown() The mouse is pressed down on the element
mouseup() The mouse is released from the element
mouseover() The mouse hovers over the element
mouseout() The mouse hovers out of the element
focus() input elements are selected
blur() input elements are deselected
change() The value of the input element changes.

 

Function with Argument, Sensors

Goals

In this lesson we will handle functions as event handlers and execute them when events occur. Today we will learn about more complex functions that can be used in web programming

  • Understand the concept of functions.  
  • Learn how to create and call functions using arguments.    
  • Learn how to call functions created by others.    
  • Understand the concept of the callback function.
  • Learn how to develop a callback function to acquire sensor information.

Functions and Arguments

When calling a function, you can pass a value into it. The value passed to the function as an argument is assigned to a variable described as the parameter of the function. It can be referred to anywhere within the function’s scope. Within the parameter of the function body, we do not need to declare it using the keyword var.

JavaScript

function sum(num1, num2){
    alert(num1 + num2);
}

sum(20, 15);
// 35 is output

In the example above, calls to the sum () function on line 5 pass the numbers 20 and 15 to the sum () function. Such values are called arguments. The actual sum () function is defined from the first line to the third line.

In parentheses on the first line, variables num1 and num2 are specified. These are variables for receiving arguments for function calls, called dummy arguments. When a function is called, it operates with a value in the variable specified by the dummy argument. That is, in the above example, the calculation result of num 1 + num 2, that is, 35 is displayed by using the alert () in the second row.

The following figure shows the concept of functions, dummy arguments, and return values so that they can be more intuitively understood. The green part in the program on the left is executed in such a way that it is expanded to the function on the right. In this example, the return value is introduced in addition to the argument.

In this example, a function called add () is defined and used. The function called add () has two parameters, x and y as dummy arguments. In the function, these two variables are added and stored in another variable z, and z is returned to the original program by using the return statement.

Let’s look at the calling program. We define a variable called a and initialize it with 2. In the next line, the variable sum is defined. At the next assignment statement, a function called add () comes up. In calling the add () function, a value of 1 and a variable called a are specified as arguments. When the function is called, control temporarily moves to the function side, but at this time, the value specified as the argument is set to the dummy argument of the function. In this example, x is set to 1, y is set as 2 in a. Therefore, when z = x + y in the add () function is executed, x is 1, y is 2, and z is 3. After that, the return statement which is the last line in the add () function shows that the value that the function finally returns to the calling program is z. This value is called a return value. Therefore, on the caller side, the evaluation result of add (1, a) is 3, and as a result, 3 is substituted into the variable sum.

JavaScript

// called function add()
function add(x, y) {
    var z = x + y;
    return z;
}

// Calling function
function lec01_02_click() {
    var a = 2;
    var sum;

    sum = add(1, a);

    alert('sum = ' + sum);
}

Callback Function

Since JavaScript expresses all values as “objects”, anything can be stored in a variable. Therefore, you can pass functions as arguments when calling functions. It is possible to create a mechanism in which a function is registered as an argument. For example, the function is called by some event such as the completion of a process, and as a result the value of the sensor changes. A function registered in preparation for such an event is called a callback function. For specific examples, please refer to the section on how to use the sensor from the next chapter.

Ambient Light Events

The Device APIs Working Group of the World Wide Web Consortium (W3C) standardizes the API for using many sensor information. Among them, there is an illuminance sensor that can be used with iMac. Let’s use it here.

Look at the next program. In the HTML section, a text area is created, followed by the unit “lux”. lux is a unit representing illuminance. In the JavaScript section, we first define a function called light_print (). This function is a callback function called when there is a change in illuminance.

Since it is decided by the API that a function to be called when the illuminance is changed takes one argument, its argument is received as a formal argument “event”. From the 2nd line to the 3rd line, the text area is acquired and the actual illuminance value is set in the text area. The sixth line is the part executed when the program is read. Here, ‘devicelight’ represents an illuminance sensor. When there is a change in the value of the illuminance sensor, light_print () set as the second argument and is called. Please note that once you set it, this function will be called each time the value changes.

HTML

&lt;input type="text" id="lighttext" value="Change the exposure of your computer camera please"&gt; lux

JavaScript

function light_print(event) {
	var elm = document.getElementById('lighttext');
	elm.value = event.value;
}

window.addEventListener('devicelight', light_print);

The iMac’s illuminance sensor is next to the camera. When you move your hand over or away from the camera part, the value detected by the illuminance sensor changes.

The use of sensor information in JavaScript is still in the development stage. Although it is already supported by many smartphones, even fixed PCs often have sensors built in, they cannot be used with JavaScript in many cases. Also, the functions that can be used also depend on the browser. Actually, the light sensor can be used in Firefox, but it cannot be used in Mac OS X’s Safari.

Timer

When you start to use sensor information etc, you may want to process it regularly. We will now learn how to use timers in JavaScript.

In JavaScript, it is possible to use two types of timers: a type that calls the function specified after the specified time, and a timer that calls the specified function periodically. In the former case, once the function is called, it is terminated. In the latter case, for example, the function is called repeatedly every 3 seconds.

Look at the program below. In this program, we first define a callback function called timeout_callback (). When this function is called, an alert is displayed. In the fifth line, timeout_callback () is set to be called after 10000 ms (10 seconds later). Therefore, when this program is executed, an alarm written as “timeout!” Is displayed after 10 seconds.

JavaScript

function timeout_callback() {
  alert("timeout!");
}

setTimeout(timeout_callback,10000);

Also, although it is a similar program, the next program behaves slightly differently. The difference with the above program is that the fifth line is not setTimeout (), but only setInterval (). In this program, unlike the above, timeout_callback () is called every 10 seconds, and as a result, an alert is displayed every 10 seconds.

JavaScript

function timeout_callback() {
  alert("timeout!");
}

setInterval(timeout_callback,10000);

Also, in order to start and stop the repeatedly called timer, it is necessary to specify a timer. Since the setTimeout () and setInterval () functions return a timer object when called, you can stop the timer by storing it in a variable.

In the next program, it is possible to start and stop the timer by storing the value returned by setInterval () in a variable called timer. timeout_callback in setInterval () is the name of the function to be called when timeout occurs.

HTML




<figure class="frame">
<button onclick="startTimer()">Start</button>
<button onclick="stopTimer()">Stop</button>

JavaScript

var timer = null;

function startTimer() {
    if (timer == null)
        timer = setInterval(timeout_callback, 3000);
}

function stopTimer() {
    if (timer != null)
        clearInterval(timer);
    timer = null;
}

Exercise 9-

As shown below, call the day and time as arguments, create a function that returns the subject name you are taking during that time. However, if a day-of-the-week that does not have any classes is entered, it shall be returned as “There are no courses that have been taken.”

...
var week = "mon";
var period = 1;
var title = classTitle(week, period);
...

In addition, if you create two text areas and one button, enter the day and time in each text area and press the button. Once you do, display the subject name you are registered in during that time.

Hint: Have data on the function side.

Exercise 9-

Create a web page whose value of illuminance varies as shown below by the illumination change shown in the example above.

Exercise 9-

Create a program that will create a moving bar graph when the illumination changes. Look below for a demonstration.

Exercise 9-

Create a program that will display an alert saying “alarm timeout” only once, and then after 10 seconds once the user presses the start button.

Exercise 9-

Use setInterval() to create a program that displays “timeout!” with an alert every 10 seconds after pressing the start button. Also, create a way to stop the alerts by pressing the stop button.

Exercise 9-

Create a program that takes string input through a text box, and on pressing a button, displays the characters in a string one by one in the p element prepared beforehand. The letters should be displayed one at a time after every second.

For example, if “keio” is entered in the text area and the button is pressed, display “k” in the first second, “ke” in the second second, “kei” in the third second, and “keio” in the fourth second.

Tip: To retrieve the nth character of the string, use charAt(). Use a timer to delay the display.

Exercise 9-

Create a program such that the bar chart shows the value of luminescence entering the sensor of your computer. Look at the example below for reference.

Array and Hash

Goals

Many programming languages have data structures such as arrays, and JavaScript is no exception. Today we will dive deeper into what you can do with arrays in JavaScript.

  • Understand the concept of an array.
  • Understand how to create multidimensional arrays in JavaScript programs.Learn how to refer to multidimensional arrays in JavaScript program. Learn how to add , combine, acquire and delete elements.
  • Understand the concept of a hash
  • Understand the relationship between a hash and objects in JavaScript.
  • Understand how to create a hash in JavaScript programs.
  • Understand how to refer to a hash in a JavaScript program.
  • Understand how to add, combine, acquire and delete elements in a hash
  • Understand what constitutes a strong password
  • Understand TLS

Arrays

Array declaration

An array allows you to save a lot of data (called array elements) by delimiting, or splitting, one variable into many. Data is stored in a box in an ordered format. When saving and retrieving data, we refer to the data in the form of the variable name followed by its reference number. In the array, numbers are used for subscripts, and we begin counting from 0. These subscripts are used to tell us which data element within the variable we are referring to.

Using letters, numbers start with 0. Subscript is the value written in brackets.

配列の概念
配列の概念

Methods for generating an array are illustrated below. The following examples all generate the same sequence.

JavaScript

// Method 1
var array = ['hoge', 'fuga'];

// Method 2
var array = new Array('hoge', 'fuga');

// Method 3
var array = Array('hoge', 'fuga');

// パターン4
var array = [];
array[0] = 'hoge';
array[1] = 'fuga';

// array[0] is 'hoge'
// array[1] is 'fuga'

Array manipulation

As mentioned earlier, there are many methods available for manipulating arrays. For example, if you want to concatenate two arrays, do the following.

JavaScript

var array1 = ["Ito", "Suzuki", "Tanaka"];
var array2 = ["Watanabe", "Ito", "Yamamoto"];

var array = array1.concat(array2);

In this example, each array of array 1 and array 2 is generated first, the two are combined at the fourth line, and assigned to a variable called array. As a result, the contents of array are “[” Sato “,” Suzuki “,” Tanaka “,” Watanabe “,” Ito “,” Yamamoto “].

There are various other methods as shown in the table below. However, there are some things that change the underlying sequence (destructive operation) and those that generate new arrays like concat () (non-destructive operation). We must be wary of the difference between the two.

Method Explanation
concat(ary) Constructs a new array concatenated with the array specified by ary and returns it.
join(str) Returns a string obtained by connecting each value of array with delimiter string str.
pop() It returns the element at the end of the array as a value, and then deletes the element.
push(val) Adds the value specified by val as an element to the end of the array.
reverse() Returns the reverse arrangement order of the elements of the array.
shift() It returns the element at the head of the array as a value, and then deletes that element.
slice(start[, end]) Extracts the array from the start to the (end-1)th element.
sort([func]) Sorts the elements in ascending order. You can also specify a function to use for sorting with func.
splice(start, cnt [, rep [, …]]) Replaces elements from start to start + cnt-1 in the array with rep.
toString() Returns a string of elements separated by “,”.
unshift(val) Adds the value specified by val as an element to the beginning of the array.

Also, although not a method, “length” is also a useful property of an array. You can know the number of elements of an array by using length.

Property Explanation
length Returns the number of elements in an array

Hash

Using meaningful strings for subscripts in arrays allows you to quickly retrieve values related to a string. For example, if you create an array with student ID numbers and use the name for that subscript, you can quickly retrieve the student ID number by accessing the array based on the name. Such an arrangement is generally called a hash.

Strictly speaking, there is no concept of a hash in JavaScript, but the same thing can be realized by using an Object. In the example below, the variable obj contains two values ‘taro’ and ‘jiro’, and subscripts (labels) for accessing each are ‘sato’ and ‘suzuki’.

 

JavaScript
// Method 1
var obj = { sato: 'taro', suzuki: 'jiro'};

// Method 2
var obj = { 'sato': 'taro', 'suzuki': 'jiro' };

// Method 3
var obj = {};
obj.sato = 'taro';
obj.suzuki = 'jiro';

// Method 4
var obj = {};
obj['sato'] = 'taro';
obj['suzuki'] = 'jiro';

//  Method 5
var obj = new Object();
obj.sato = 'taro';
obj.suzuki = 'jiro';

// obj['sato'] が 'taro'
// obj['suzuki'] が 'jiro'

Two dimensional arrays

When trying to store data like a spreadsheet, the functions we have seen so far may be insufficient. For example, suppose you have the following data:

Date Opening Price Max Price MIN Price Closing Price
2011/1/10 82.690000 83.540000 82.379900 82.940000
2011/1/17 82.800000 83.489900 81.819900 82.580000

This is exchange rate data for the weekly dollar yen in 2011. How can we handle this data? One possible way is to treat each column as an array.


&amp;amp;lt;figure class="frame"&amp;amp;gt;&amp;amp;lt;pre&amp;amp;gt;var date =  ["2011年1月10日", "2011年1月17日", ...];
var start = [82.690000, 82.800000, ...];
var high =  [83.540000, 83.489900, ...];
var low =   [82.379900, 81.819900, ...];
var end =   [82.940000, 82.580000, ...];

Certainly this still can handle data, but there is a better way. We can use a two-dimensional array for storing data by columns and rows as shown in the table.


var usdjpy = [

&amp;lt;figure class="frame"&amp;gt;&amp;lt;pre&amp;gt;  ["2011/1/10",82.690000,83.540000,82.379900,82.940000],
  ["2011/1/17",82.800000,83.489900,81.819900,82.580000],
  ...
];

In this example, the date, the opening price, the max price, the min price, the closing price are arranged as one row, and the array for every week is made as a column. In other words, “[” January 10, 2011 “, 82.69, 83.54, 82.3799, 82.94]] is also one array, and the whole table gathered is also an array. In the above example, the variable usdjpy contains an array within an array, or a two-dimensional array.

Now, how do we use the two dimensional array we just created? It is not difficult to use once we understand how the arrays are arranged within the 2D array. For example, to use the second column of the first row, we refer to it as”usdjpy [0] [1]”. Since the array starts from the 0th element, the subscript representing the first line is 0 and the subscript representing the second column is 1.


<figure class="frame"><pre>var usdjpy = [
  ["2011/1/10",82.690000,83.540000,82.379900,82.940000],
  ["2011/1/17",82.800000,83.489900,81.819900,82.580000]
];
 
alert(usdjpy[0][1]);

When actually executing the above program, the number “82.69” is displayed with an alert.

Security

When using computer networks, knowing about security is very important. In this section, your understanding of arrays is crucial to acquiring skills related to security.

Creating a strong password

One of the security topics that is familiar to you is a password. Passwords are used in various situations, such as logging onto a computer, or connecting to a server. When making a password, it is often said that you have to make it more than a certain length, you should mix capital letters and lower case letters, you should include numbers and symbols, and not use the words in the dictionary. Why is this? Let’s explore.

Brute force attacks

What method would you test if you were told that a certain password was broken? Perhaps the most common method you may think of is trying random combinations of numbers and letters till you get the right password. This is a lengthy process, but it is an effective means when the password is short. Therefore, using such a means is called brute force attack.

Have you ever seen a key of the type shown below? This key has numbers 0 to 9 written in each ring, you can open the key by matching the three numbers.

key

If you know that it is a three-digit password of numbers from 0 to 9, how long will it take for the computer to solve that password? See the next program. In this program, the time is measured before and after the for loop of the triple loop, and the difference, that is, the time taken is displayed by alert (). Numbers from 000 to 999 are displayed in the three level nested loop portion. It can be confirmed that counting from 0 to 999 takes little time for a computer.

HTML

<input type="button" value="Brute force attack on three digit number, each digit is from 0~9" onclick="n3()">
<input type="text" id="text080201" value="000">

JavaScript

function n3() {
    var str = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
    var ele = document.getElementById("text080201");

    var t_start = (new Date).getTime();

    for (var i=0; i&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; i++) {
        for (var j=0; j&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; j++) {
            for (var k=0; k&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; k++) {
                ele.value = str[i] + str[j] + str[k];
            }
        }
    }

    var t_end = (new Date).getTime();

    alert("Time Taken: " + (t_end - t_start) + "ms");
}

As you can see, the time taken for the computer to count from 0 to 999  is very little. For this reason, passwords with short character strings of only numbers are not recommended.

So how will it change when you use lower case alphabets?

HTML

&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;input type="button" value="Brute force attack on three digit number, each digit is from 0~9 and lower case a~z" onclick="na3()"&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;
&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;input type="text" id="text080202" value="000"&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;

JavaScript

function na3() {
    var str = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
               "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
               "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
    var ele = document.getElementById("text080202");

    var t_start = (new Date).getTime();

    for (var i=0; i&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; i++) {
        for (var j=0; j&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; j++) {
            for (var k=0; k&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;str.length; k++) {
                ele.value = str[i] + str[j] + str[k];
            }
        }
    }

    var t_end = (new Date).getTime();

    alert("Time taken:" + (t_end - t_start) + "ms");
}

We can now confirm that the second password generated from alphabets and numbers took longer to crack.

Dictionary Attack

Then, is it safe to just increase the type of letters or increase the number of digits? Not really. If you use a common word as a password, you may unexpectedly get your password hacked. In an attack called a dictionary attack, the attacking side has a dictionary and has tried each word in it till they matched your password.

For example, suppose that there is a character string "university". Since there are 10 characters, it takes a reasonable amount of time in brute force attack. However, using a dictionary attack, the hacker can arrive at the password a lot sooner in their iterations. The number of words in the English dictionary is at most in the order of a few hundred thousands. Let's estimate a little more and try it with a password using a one million word dictionary. This will take the same amount of time as trying a password of 6 digits (000000 - 9999999), which is not a lot of time for computers.

For these reasons, when attaching a password, it is said that "you must make it longer than a certain amount, you should mix capital letters and lower case letters, you should include numbers and symbols, and not use the words in the dictionary.

Web page password authentication

When you are accessing a web page, you may be prompted for a password. This is made possible using functions called Basic Authentication and Digest Authentication. Both Basic Authentication and Digest Authentication authenticate users with ID and password pairs, but in the case of Basic Authentication, unencrypted passwords flow through the network. For this reason, Digest Authentication should be used as much as possible. Previously, some browsers did not support Digest Authentication, but now almost all browsers support it.

In addition, it is also possible to encrypt the communication path itself by using TLS (described later). In this case, the password will flow through the encrypted communication path even in Basic Authentication.

The basic usage of Digest Authentication is to ask for an ID / password to access under a certain directory. For example, ask for ID / password when accessing under the directory public_html / info 2/08, that is, accessing https://web.sfc.keio.ac.jp/~ [login name] / info 2/08 / In order to do so, you need to create a file called public_html / info2 / 08 / .htaccess. In public_html / info2 / 08 / .htaccess, write the following contents. Please note that you put a blank line at the end.

 

AuthUserFile	/home/[loginName]/.htdigest
AuthName	"Members Only"
AuthType	Digest
require 	valid-user
 

After that, create a Digest file. A Digest file is created by launching a terminal as follows. Here, the line starting from "$" is part of the line for input. However, there is no need to enter "$" at the prompt.

$ /usr/sbin/htdigest -c ~/../.htdigest "Members Only" [userName1]
Adding password for [userName1] in realm Members Only.
New password:
Re-type new password:
$ /usr/sbin/htdigest ~/../.htdigest "Members Only" [userName2]
Adding password for [userName2] in realm Members Only.
New password:
Re-type new password:

"- c" in the first line specifies to create a new file. When adding the second and subsequent users, do not specify "-c". For [user name 1] [user name 2], specify the user name you want to use for login. Then you will be prompted for a password so enter twice. This will create a Digest file.

For more details, please refer to http://www.sfc.itc.keio.ac.jp/en/network_web_server.html.

TLS

Previously, in order to access the created Web page, we use a URL like "http: // ...". This shows that you use plain HTTP to access the web. However, in plain HTTP, communication is not encrypted, and if communication is intercepted, communication contents may be eavesdropped.

To solve this problem, we use Transport Layer Security (TLS). In the past, a technology called Secure Sockets Layer (SSL) was used, but now a more sophisticated TLS that supports strong encryption has been developed. However, even though TLS is actually used in the world, many websites still call it  "SSL communication", so it can be a little confusing.

When accessing the Web using TLS, use "https: // ..." instead of "http: // ...". The last "s" indicates that TLS is used. By specifying "https: // ...", the version of the protocol actually used between the Web server and the Web browser is adjusted, and the encrypted communication path is established.

 

https

Generally when a TLS connection is established, a server called "server certificate" is sent from the server side to the client side. For checking the server certificate, a public key cryptosystem cipher is used. Characteristics of public key cryptography are as follows. In the public key cryptosystem, a publicly-known key called a public key and a key pair known only to the user called a secret key are used. A document encrypted with a secret key can be decrypted with a public key, and a document encrypted with a public key can be decrypted with only a secret key. For this reason, when viewing a document encrypted with a secret key, it can be confirmed that only the person who has a secret key made the encrypted sentence. Conversely, documents encrypted with a public key can only be decrypted by a person with a secret key.

In order to check if the communication partner is the intended server indeed, we need to confirm the "server certificate". An organization called certification authority signs (encrypts) it with a secret key. Since the public key of the certificate authority is widely distributed, anyone can confirm (decrypt) whether the "server certificate" sent using the key is correct or not. The certificate authority is managed in a hierarchical structure, and the public key of the certificate authority, which is a major part of it, is distributed across all browsers.

Exercise 8-

Create a simple fortune teller program using arrays. The JavaScript skeleton is as follows.

function mikuji(){
  var unsei = new Array("Good Luck","Medium Luck","Moderate Luck","Little Luck","No luck","Bad Luck","Disaster");
  var uranau = /* Write here */;

  document.getElementById("res").innerHTML = /* Write here */;
}

Exercise 8-

Create a program that simulates the three digit brute force attack shown in the above example and displays the time taken.

Exercise 8-

Create a program that tells you the time you spent trying a brute force attack with 3 digits of alphanumeric characters using only lowercase letters.

Exercise 8-

Create a program that displays alphanumeric three-digit brute-force attacks using both uppercase letters and lowercase letters and displays the time taken in the text area.

Exercise 8-

Create a program that shows the 6 digit brute force attack and displays the time taken in the text area. The time taken is the same as that for a dictionary attack using a dictionary of 1 million words.

Exercise 8-

Certification authorities are the agencies that issue certificates, and in many cases are private corporations. Also, because the certificate is an electronic file, it costs very little to generate. This means that getting into such a business could be very profitable, however this is not true. Think about why it is difficult to launch a certificate authority, and create a web page showing that idea.

Also make Digest Authentication so that you can access it on ID: info2, Password: Keio # University

Canvas and Nested Loops

Goals

In this lesson we will look into nested loops. Multiple iteration is merely a single nested structure where loops exist inside other loops. If you understood how loops work, understanding nested loops should not be difficult to grasp.

We will also learn how to render Java canvas elements with JavaScript.

  • Understanding the behavior of nested loops in a while statement.
  • Understanding the behavior of a nested for loop.
  • Understanding how to track changes in variables in nested loops
  • Understanding how to use three level or more nested loops effectively
  • Learning how to render Canvas elements with basic shapes such as circles and rectangles.
  • Drawing complicated figures on the canvas element

 

canvas and drawing

Before describing the canvas and rendering nested loops, let’s look into what the canvas element is as an element in HTML.

The canvas element

The canvas element is an element for securing a drawing area on a Web page. Below is an example on how to create a canvas element in HTML.

A drawing area of 200 × 200 is fixed when we create a canvas of size 200×200 pixels. “Rectangle drawing area” enclosed by tags is a character string displayed as an alternative when this page is displayed in browsers that do not support the canvas element. As long as you use the latest version of browsers such as Firefox or Safari, such a character string will never be displayed.

HTML

 <canvas id="canvas" width="200" height="200">Rectangular drawing space</canvas>

 

Just inserting the canvas element into an HTML document merely leaves space on the page. This space is now empty and only contains the placeholder text that we wrote. In order to actually utilize the canvas element, it is necessary to draw it using JavaScript.

Basics of drawing with JavaScript

In order to draw within the drawing space fixed by the canvas element using JavaScript , it is necessary to acquire the canvas element in the program and obtain the drawing context thereafter. The context is what allows us to manipulate the empty space in the canvas element for drawing.

HTML

<canvas id="canvas" width="200" height="200">Rectangular drawing space</canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.strokeRect(50, 50, 100, 100);

The above program draws a square using the canvas element. The canvas element is acquired in the first line of JavaScript. By acquiring the canvas element, we can perform actions such as drawing, using programming and basic mathematics.

In the second line, the context for two-dimensional rendering is acquired. The context may be difficult to understand, but it is used to define what kind of coordinates are used, what kind of graphics can be specified and what kind of sizes and colors are to be filled in. In other words, by specifying ‘2d’ here, we get a 2D rendering context. The fact that there are two dimensions means that if you write ‘3d’, you can also draw three dimensions, but unfortunately the only drawing context you can currently use is ‘2d’. In the future it may become possible to use 3D drawing contexts as well.

Once you get the drawing context of the canvas, you can change some of the properties that exist in it. For example, you can change the line color and thickness to suit your preference. In order to change the thickness of a line with JavaScript, after acquiring the drawing context ctx (We don’t have to name it ctx but let’s keep it that way for convenience), we can change the lineWidth property. Also, to change the line color, change the strokeStyle property. You can specify the color for filling, by changing the fillStyle property.

Look at the next program. Line thickness, color, and fill color are specified from line 4 to line 6 of JavaScript. Also, in the eighth and ninth lines, filled squares are drawn and rectangular boxes are drawn.

Looking at the HTML part of this program, usually the script element is contained in the header. This is to allow you to load the program after creating the canvas element. Normally, this kind of operation is not performed, and the onload event is used, but this time, please execute the program in this way.

HTML

<!DOCTYPE html>
<html>

  <head>
    <meta charset="utf-8">
    <title>描画の例</title>
  </head>

  <body>
    <h1>描画の練習</h1>
    <canvas id="canvas" width="200" height="200">四角形を描画する領域</canvas>
    <script src="draw.js"></script>
  </body>
</html>

JavaScript(draw.js)

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.lineWidth = 10.0;
ctx.strokeStyle = 'black';
ctx.fillStyle = 'lightgrey';

ctx.fillRect(50, 50, 100, 100);
ctx.strokeRect(50, 50, 100, 100);

Basic drawing using JavaScript

When we render images onto our canvas we must understand what a path is. A path is used to draw complex figures by combining a number of mathematical and graphical methods. Imagine you are holding a pen and giving it instructions where to move and whether to touch the paper or not. In essence, the path is the journey traveled by a pen over the paper when making a drawing.

For example, the method for drawing hexagons does not exist in the two-dimensional drawing context, but you can draw a hexagon using a path.

  • Here, the path from the beginPath() method to the closePath() method is the part defining the path.
  • We use the moveTo() method (to move from start point to end point without touching the canvas) or the lineTo() method (to move ) to select a starting point and draw the first line.
  • We draw a hexagon by specifying the co-ordinates
  • We fill it with color with the fill() method
  • After that we color the line using the stroke () method.

Note that until you color it with the fill () method or the stroke () method, it does not actually look like a visible shape.

HTML

<canvas id="canvas" width="200" height="200">Hexagon is drawn here</canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var x = 100;  // X co-ordinate of the center
var y = 100;  // Y co-ordinate of the center
var r = 80;   // Radius

ctx.lineWidth = 3.0;
ctx.strokeStyle = 'black';
ctx.fillStyle = 'lightgrey';

ctx.beginPath();
ctx.moveTo(x + Math.sin(0 * 2 * Math.PI / 6) * r, y - Math.cos(0 * 2 * Math.PI / 6) * r);
ctx.lineTo(x + Math.sin(1 * 2 * Math.PI / 6) * r, y - Math.cos(1 * 2 * Math.PI / 6) * r);
ctx.lineTo(x + Math.sin(2 * 2 * Math.PI / 6) * r, y - Math.cos(2 * 2 * Math.PI / 6) * r);
ctx.lineTo(x + Math.sin(3 * 2 * Math.PI / 6) * r, y - Math.cos(3 * 2 * Math.PI / 6) * r);
ctx.lineTo(x + Math.sin(4 * 2 * Math.PI / 6) * r, y - Math.cos(4 * 2 * Math.PI / 6) * r);
ctx.lineTo(x + Math.sin(5 * 2 * Math.PI / 6) * r, y - Math.cos(5 * 2 * Math.PI / 6) * r);
ctx.lineTo(x + Math.sin(6 * 2 * Math.PI / 6) * r, y - Math.cos(6 * 2 * Math.PI / 6) * r);
ctx.closePath();
ctx.fill();
ctx.stroke();

There is another thing to be careful about here. In the normal graph, the number increases from left to right on the X axis and from the bottom to the top on the Y axis, but when drawing with the canvas element, the number increases from the top to the bottom on the Y axis. Please note this point when calculating the coordinates.

canvasの座標系
canvasの座標系

methods for drawing

Below is a summary of the representative methods used for drawing. These have been written for you by developers all over the world, so you are free to use them to draw in your own programs.

Method Explanation
fillRect(x, y, w, h) Draws a rectangle without filled boxes of width w and height h from the coordinates specified by (x, y) as a starting point. Unlike lineTo () etc., a rectangle is actually drawn without using stroke () method or fill () method.
strokeRect(x, y, w, h) Draws a rectangle with unfilled frame of width w and height h from the coordinates specified by (x, y) as a starting point. Unlike lineTo () etc., a rectangle is actually drawn without using stroke () method or fill () method.
clearRect(x, y, w, h) Deletes figures in the range of width w and height h from the coordinates specified by (x, y) as a starting point.
moveTo(x, y) With the pen tip raised, move the pen tip to the coordinates specified by (x, y).
lineTo(x, y) Draws a straight line from the position where the pen tip is present to the coordinate specified by (x, y).
rect(x, y, w, h) Draws a rectangle of width w and height h starting from the coordinates specified by (x, y).
arc(x, y, r, sAng, eAng, anticlockwise) Draws an arc of radius r from the angle specified by sAng centered on (x, y) to the angle specified by eAng. In addition, counterclockwise when anticlockwise true, and clockwise when false.
bezierCurveTo(x0, y0, x1, y1, x2, y2) Draw a cubic Bezier curve. Draws a Bezier curve with the current coordinates as the start point, (x 2, y 2) as the end point, (x 0, y 0) as the control point for the start point and (x 1, y 1) as the control point for the end point.
fillText(text, x, y) fillText (text, x, y) Write the character string specified by text to the coordinate (x, y). You can change the font by changing the font property of the drawing context like “ctx.font =” 20pt Mincho “;”

If you want to erase the entire canvas, you can use clearRect () to make it “ctx.clearRect (0, 0, canvas.width, canvas.height);”, where ctx is the drawing context. Also, canvas is a variable containing a canvas element. For canvas.width and canvas.height, the width of the canvas and the height of the canvas are automatically set.

Nested Loops

Two Level Nested Loops

Regarding iteration, we have already explained that while statements and for statements exist. However, using a while loop or for loop singly can sometimes run out of functionality. Consider using the previous canvas element to draw a pattern like the checker flag like this:

In order to draw such a pattern, of course, there is also a way to program it in HTML and JavaScript:

HTML

<canvas id="canvas" width="200" height="200">Canvas Element Here</canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

ctx.fillRect(  0,   0, 20, 20);
ctx.fillRect( 40,   0, 20, 20);
ctx.fillRect( 80,   0, 20, 20);
ctx.fillRect(120,   0, 20, 20);
ctx.fillRect(160,   0, 20, 20);
 
ctx.fillRect( 20,  20, 20, 20);
ctx.fillRect( 60,  20, 20, 20);
ctx.fillRect(100,  20, 20, 20);
ctx.fillRect(140,  20, 20, 20);
ctx.fillRect(180,  20, 20, 20);
 
ctx.fillRect(  0,  40, 20, 20);
ctx.fillRect( 40,  40, 20, 20);
ctx.fillRect( 80,  40, 20, 20);
ctx.fillRect(120,  40, 20, 20);
ctx.fillRect(160,  40, 20, 20);

...

However, it seems that computers can make this process faster and more efficient. If we automate some of the processes by using a loop we can make the program faster and easier to process. Look at the next program.

HTML

&amp;amp;amp;amp;amp;lt;canvas id="canvas" width="200" height="200"&amp;amp;amp;amp;amp;gt;四角形を描画する領域&amp;amp;amp;amp;amp;lt;/canvas&amp;amp;amp;amp;amp;gt;

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var y;
for (y=0; y&amp;amp;amp;amp;amp;lt;200; y = y + 20) {
  if (y % 40 == 0) {
    ctx.fillRect(  0, y, 20, 20);
    ctx.fillRect( 40, y, 20, 20);
    ctx.fillRect( 80, y, 20, 20);
    ctx.fillRect(120, y, 20, 20);
    ctx.fillRect(160, y, 20, 20);
  } else {
    ctx.fillRect( 20, y, 20, 20);
    ctx.fillRect( 60, y, 20, 20);
    ctx.fillRect(100, y, 20, 20);
    ctx.fillRect(140, y, 20, 20);
    ctx.fillRect(180, y, 20, 20);
  }
}

However, program also has parts that are redundant. We can make this process even simpler by adding another loop within this for loop.

HTML

<canvas id="canvas" width="200" height="200">四角形を描画する領域</canvas>

JavaScript

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var x, y;
for (y=0; y&amp;amp;amp;amp;amp;lt;200; y+=20) {
  for (x=0; x&amp;amp;amp;amp;amp;lt;200; x+=20) {
    if ((x+y)%40 == 0) {
      ctx.fillRect(x, y, 20, 20);
    }
  }
}

In this example, the loop controlled by the variable y contains a loop controlled by the variable x. This is a two level nested loop. A flowchart of this nested loop is shown below. It may seem complicated at first, but you should be able to understand it once you check each flow.

 

二重ループのフローチャート
二重ループのフローチャート

Exercise 7-1

  1. Create an HTML file marked * above and draw.js and run the program.
  2. Create a program that swaps  ctx.fillRect () with ctx.strokeRect () and see what happens.

Exercise 7-2

Create a program that draws n squares by entering n as shown below.

Exercise 7-3

Using the above program, create a program to find π by increasing the number of sides in a polygon and dividing the circumference by its diameter.

Exercise 7-4

Draw the asterisk as shown below.

Exercise 7-5

Draw the following figure.

Exercise 7-6

Draw the following figure

Exercise 7-7

Draw the following figure

Exercise 7-8

As shown below, create a program to find π by Monte Carlo method while displaying points. Also, be sure to increase accuracy as you press the button. In order to calculate π by the Monte Carlo method, consider the circle inscribed in a square, select an appropriate point, and check whether that point falls inside the circle. On that basis, π is calculated from the ratio of points entering the circle.

Array, HTML and JavaScript

Goals

Here we will learn about simple objects and one-dimensional arrays, as well as how to handle HTML elements from JavaScript.

  • Understand the concept of one dimensional arrays.
  • Understand how to use getElementsByTagName ()
  • Understand how to use  getElementById ()
  • Understand how to use getElementsByClassName ()
  • Understand how to use  operate DOM elements with JavaScript.
  • Understand the structure of values returned by getElementById (), getElementsByClassName (), etc.

Objects

An object is a collection of values. For example, an object called name is made of “first name” and “last name”.  An object called a position may be made up of “latitude” and “longitude”. Likewise, an object representing a person can be expressed as an object named “name”, along with their “first name”, “last name”, “age” and “sex”.

名前の構造

位置の構造

人の構造

Object Literal

In JavaScript, an object literal is used to express an object using actual values. An object literal has the following format.

{
Property Name: Value,
Property Name: Value,
...
}

A property name is a name given to each value existing in an object. For example, if you write a person’s name as an object literal, you can write something like this:

The value is enclosed in double quotes like “Keio” and “Taro”, because the value is a character string.

{
familyName: "Keio",
firstName: "Taro"
}

Property names can use arbitrary character strings, including spaces. If it contains spaces, it is necessary to enclose the property name in single quotes or double quotes. However, since there are restrictions on referring to objects that are to be reused later in the program, it is better to avoid using spaces or “-“. You may use kanji and hiragana, but it would be better to stick to roman characters.

{
familyName: "Keio",
firstName: "Taro"
}

Also, in the case of an object containing other objects like a person, it is possible to describe it as shown below. Here, pay close attention because the property “name” is drawn to the object “{familyName:” Keio “, firstName:” Taro “}}”.

{name: {familyName: "Keio", firstName: "Taro"}, age: 19, sex: "male"}

Object Declaration

It is easy to create variables containing objects. We will now look at creating an object that is initialized before the program is executed.

var variableName = {
propertyName: value, propertyName: value,
...
};

For example, if you want to create a human object you can do as follows.

var human = {
name: {familyName: "Keio", firstName: "Taro"},
age: 19, sex: "male"
};

Note: We have put in line breaks between the curly brackets {} so that the code is easier to read, but for practical purposes there is no need to have the contents of the object on different lines.

In JavaScript, there is another method of generating an object using the new operator. To create an object using the new operator, use a constructor. We will not go into details here, but the Date() object is one kind of object that uses the new operator. In a program using Date (), create an object as follows.

var date = new Date();

This uses a Date object which is an object provided by the system, creates a new object that has various functions that can be used, and assigns it to the variable date.

A function such as toLocaleString () (a function attached to an object is called a method) is defined as a member of the Date object beforehand, and these can be used through the variable date.

In other words, functions can be stored in the object and used using the object name. We will discuss this in greater detail later.

Referencing Objects

If you put an object into a variable, you must think about how you will use it. In order to refer to the value in the object in the program, it is written as follows:

variableName.propertyName;
variableName["propertyName"];
variableName['propertyName'];

Every row represents the same value, but if we use the first method to express the object, we must be careful. A problem arises if the property name is a number “123” or includes minus like “first-name” and does not conform to the naming convention of variable names. This is the main reason why it is better to not use strings such as blanks or minus as we mentioned before.

Also, in the above example of a human as an object, familyName is in the object name. We therefore have variable stored within other objects. We may refer to the properties as follows:

variableName.propertyName1.propertyName2;
variableName["propertyName1"]["propertyName2"];
variableName['propertyName1']["propertyName2"];

Specifically, the portion containing the value “Keio” is as follows.

human.name.firstName;
variableName["name"]["firstName"];
variableName['name']["firstName"];

With that said and done, how do you use these properties in an actual program? The following is an example of generating an object “human” and displaying the value of each property contained in the object. In this example, we use different expressions such as “human.name.familyName” ,”human.name [” firstName “]” to indicate that there are various  different expressions, but it is not possible to mix up expressions unnecessarily. Care must be taken to improve the readability of the program.

/* *
Object Creation
*/

var human = {
name: {familyName: "慶應", firstName: "太郎"},
age: 19, sex: "male" };

/* *
プロパティの表示
*/

alert("姓: " + human.name.familyName);
alert("名: " + human.name["firstName"]);
alert("年齢: " + human.age);
alert("性別: " + human['sex']);

 

One Dimensional Arrays

Many programming languages have a mechanism called an array to handle data of larger sizes. JavaScript is no exception. An array is one way to store multiple values within one variable name, followed by a number to reference each value.

配列

A place where each value in an array can be stored is called an “element”. As mentioned above, in the case of arrays, there is only one variable name for the whole array. The whole array is a collection of many elements. Each element can be used like the variables we learned about so far. We must also be careful to note that when referring to array elements and retrieving values, our style of declaration and referencing is different from ordinary variables.

Array Literal

Literals are determined for arrays as well. The array literals are as follows.

[value, value, value, ...]

The number of values is arbitrary, and it is possible to specify as many as 0 or more necessary numbers. In the case of 0, an empty array is generated.

This is how it looks with real data.

["佐藤", "鈴木", "田中", ...]

In the above example, all element values are character strings, but in JavaScript you can change the value type for each element. For example, if you write “[” a “, 3]”, the value of the first element is a character string, but the value of the second element is treated as a numeric value. Furthermore, it is also possible to create an array of objects, or to specify an array as one of the properties of the object.

Array Declaration

Even when declaring an array, there are many methods for generating an array initialized with an array literal as well as an object, and even a method using a constructor.

Here we will look at a method using array literals. The method using an array literal is simple and it is as follows:

var variableName = [value, value, value, ...];

In the following example, an array containing three character strings “” Sato “” “Suzuki” “” Tanaka “” is assigned to a variable named familyName.

var familyName = ["Sato", "Suzuki", "Tanaka"];

Also, to create an empty array (an array with no elements):

var familyName = [];

Array Manipulation

Various methods are prepared to perform operations on and manipulate array objects. Here are some of them.

Adding new elements to an array

Add element at the beginning (unshift)
var array = ['b', 'c'];
array.unshift('a');
alert(array); // ['a', 'b', 'c']
Add an element to the end (push)
var array = ['a', 'b'];
array.push('c');
alert(array); // ['a', 'b', 'c']

Combining elements of an array

Creating an array by combining two arrays (concat)
var array1 = ['a', 'b'];
var array2 = ['c', 'd'];

// New Array
var array = array1.concat(array2);

alert(array); // ['a', 'b', 'c', 'd']
alert(array1); // ['a', 'b']
alert(array2); // ['c', 'd']

Retrieving information from an array

Get the number of elements in an array (length)
var array = ['a', 'b', 'c'];
var len = array.length;
alert(len); // 3
Get the value of a specific element in an array (if the same element exists more than once then the first element) (indexOf)
var array = ['a', 'b', 'c'];
var index = array.indexOf('b');
alert(index); // 1
Get the position of the last occurrence of an element(lastindexOf)
var array = ['a', 'b', 'c'];
var index = array.lastIndexOf('c');
alert(index); // 2

Deleting elements in an array

Delete the first element (shift)
var array = ['a', 'b', 'c'];
array.shift();
alert(array); // ['b', 'c']
Delete the last element (pop)
var array = ['a', 'b', 'c'];
array.pop();
alert(array); // ['a', 'b']

Sort element contents alphabetically

var array = ["e", "c", "b", "a", "d"];
array.sort();
alert(array); // ["a", "b", "c", "d", "e"]

Referencing an array

Referencing an array is similar to referencing an object. Add a bracket after the variable name and specify a number within it. For example, to refer to the second element in the array named array, it is expressed as follows.

array[1];

The thing to notice here is that the array index starts at number 0. The first element of the array is at the 0th index, the second at the 1st index, the third at the 2nd index and so on.

You can also specify variables instead of numbers.  In the example below, an array is created on the first line, and 1 is assigned to the variable n at the third line. In the fourth line, the nth element counting each element of the array starting from 0 is displayed.

var array = ["Sato", "Suzuki", "Tanaka", "Watanabe", "Ito "Yamamoto"];
var n = 1;
alert(array[n]);//Suzuki

Also, by combining an array with a for statement, it is possible to output all the elements in order. In the example below, we use the length property to create a iteration with a for statement and display “The element at position n  of the array is: xx” for all the array elements.

var array = ["Sato", "Suzuki", "Tanaka", "Watanabe", "Ito "Yamamoto"];
var i;
for (i = 0; i &amp;amp;lt; array.length; i++) {
alert("The element at position "+ i + "of the array is: " + array[i]);
}

Objects and Arrays

In fact, there are similarities in objects and arrays, as you can see from their representation methods. You can also refer to an object’s property with a “.” as you can with an array.

However, it is not possible to express “obj.0”, “obj.1”, “obj [0]”, “obj [1]” and so on, so be careful. In this case, it is necessary to express it as “obj [” 0 “]” “obj [” 1 “]”. A property is a string in an object, but in an array it is a number.

Linking HTML and JavaScript

Elements and Naming

In HTML, an ID and class can be attached to each element. By attaching IDs and classes, we are able to specify styles with CSS only for that element. Even in JavaScript, adding an ID or class makes it easier to specify the element.

id

The id attribute gives a unique ID (identifier) ​​for referring to an element. It is not possible to have the same ID in one document or webpage (that is, it must be unique).

The purpose of specifying the id attribute is to designate elements to be decorated with CSS and to perform processing by referring to specific elements in JavaScript.

This ID can be specified in a div element, a heading element or any other opening tag.

class

The class attribute specifies the class name for that element. Unlike the id attribute, the class attribute can use the same class name many times in one document. Also, it is possible to apply multiple classes to one element, separated by single-byte spaces.

Handling elements with JavaScript

When referring to an HTML element from JavaScript, it is necessary to first incorporate the element into a JavaScript program. Here, we will explain the connection between HTML elements using IDs and classes in JavaScript.

getElementById()

A getElementById () method is prepared in the document object as a function for linking HTML elements by specifying an ID from JavaScript. The getElementById () method takes an ID as an argument and returns an HTML element with that ID. By assigning a return value to a variable, it becomes easy to access that element from JavaScript.

HTML

...
&amp;lt;p id="p1234"&amp;gt;テスト1&amp;lt;/p&amp;gt;
テスト2

&amp;lt;button onclick="showContent();"&amp;gt;Click Me&amp;lt;/button&amp;gt;
...

JavaScript

function showContent() {
var ele = document.getElementById("p1234");
alert(ele.innerHTML);
}

テスト1

テスト2

In the above JavaScript, an element whose ID attribute is p1234 is assigned to a new variable ele. After that, HTML for the element whose ID is p1234, i.e. , all the HTML code written between the start tag with the specified ID and the end tag is stored in ele.

getElementsByClassName(“ClassName”)

getElementsByClassName () gets all the elements with the specified class attribute. In the example below, an element with a class attribute “aaa” is acquired. Here, there is a possibility that there are two or more elements having the class attribute “aaa” (in fact, in the example below, multiple elements have the class attribute “aaa”), and the return value is stored in an array.

HTML


Element 1

Element 2

Element 3

Element 4

Element 5

&amp;lt;button onclick="numOfaaa();"&amp;gt;Click Me&amp;lt;/button&amp;gt;

JavaScript

function numOfaaa() {

var classes = document.getElementsByClassName("aaa");

alert(classes.length);
}

Element 1

Element 2

Element 3

Element 4

Element 5

Multiple class names can also be specified simultaneously in JavaScript so that you can specify multiple class attributes in one tag. When specifying more than one, specify by separating with space as follows.

HTML


Element 1

Element 2

Element 3

Element 4

Element 5

&amp;lt;button onclick="numOfaaaacccc();&amp;gt;Click Me&amp;lt;/button&amp;gt;

 

JavaScript

&amp;lt;="" p=""&amp;gt; function numOfaaaacccc() {
var classes = document.getElementsByClassName("aaaa cccc");

alert(classes.length);
}

 

Element 1

Element 2

Element 3

Element 4

Element 5


getElementsByTagName(“tagName”)

getElementsByTagName () is a method for specifying a tag name to obtain an HTML element. Like getElementsByClassName (), getElementsByTagName () also gets all the elements with the specified tag name and returns an array. In getElementsByTagName (), regardless of whether the id attribute or the class attribute is added, all items with the specified tag name are acquired.

HTML


Element 1

Element 2

Element 3

Element 4

Element 5

JavaScript

var pAll = document.getElementsByTagName("p");
alert(pAll.length);

 

DOM

The HTML document has a tree structure as described above. So, how do you show “where is the HTML document?” Use DOM to solve this problem. DOM is an abbreviation of Document Object Model, and is an arrangement for handling a document as an object. It seems difficult, but basically it is equivalent to the tree structure mentioned above. Let’s look at this in a little more detail.

See the figure below. This figure is a diagram in which the node “document” has a tree structure illustrating all its child elements, much like the tree structure we looked at before.

DOM

We introduced a function called document.getElementById () above. Actually, this is exactly the same interface as the DOM model itself. The meaning of this function is that it brings an element with the specified ID from the document document (the object at the top level of all HTML documents is the document in JavaScript). That is, the tree structure above is searched and the node with the specified ID is taken as the return value.

The object containing the element has various properties (values) that can be manipulated. For example, if you specify a property named firstChild for an element, you can get the first child element and you can get the second child element by specifying the property childNodes [1]. Here, the inside of the bracket is 1 because in JavaScript, the array starts at 0.

For example, an element containing the title “JavaScript” can be specified as follows:

 document.childNodes[1].firstChild.childNodes[1];

However, care should be taken because if there is a line break or an empty space between the tag and the tag in the HTML file, the newline or blank may be recognized as an element. It may be necessary to write it without including a line break as follows:

In addition, there are various properties other than firstChild and childNodes in the object storing the element. For example, in the property called innerHTML, the HTML code within the tree structure containing that element is obtained. An example of the property is shown below.

Property Explanation
attributes[] An array storing the attributes of a node
childNodes[] An array storing the child nodes of an element
firstChild The first child node of an element
innerHTML The HTML code present between the start and end tags of the element
innerText The text present between the start and end tags of the element
lastChild The last child node of an element
parentNode The parent node of the element
style The style attribute of the element that can be manipulated
value The value of the node

Exercise 5-1

Use prompt() is to input six names into an array, and create a program to display it with alert () three names at a time.

Exercise 5-2

Create a program to accept an input of five character strings using prompt () and display them one by one in alphabetical order by alert ().

Hint: You can use the sort () method.

Exercise 5-3

Create a program that creates a page that contains multiple p elements, counts the number of p elements using getElementsByTagName (), and displays that number with alert ().

Exercise 5-4

When you have the following HTML, create a button to change the contents of elements containing ccc, aaa and bbb.


Element 1

Element 2

Element 3

Element 4

Element 5

Element 1

Element 2

Element 3

Element 4

Element 5

Loop

Goals

In programming, repetition is an important part in conditional branching. In today’s lesson we will learn about repetition in JavaScript. We will also look to understand what blocks and statements are with respect to repetition

  • Understanding sentences and blocks.
  • Understanding the behavior of the while statement. Writing while statements correctly.
  • Understanding the behavior of the for statement. Writing a for statement correctly.   
  • Rewriting the iteration written in the while statement with the for statement.   
  • Rewriting the iteration written in the for statement with the while statement. 
  • Understanding the behavior of repeated use of the continue statement.
  • Understanding the behavior of iteration using a break statement.

Sentences and Blocks

Last time we learned that the if statement uses specific syntax. In this example of an if statement, the parts surrounded by curly brackets “{” and “}” are executed or not, depending on the conditions of the if and else statements that surround it.

if (condition 1) {
/* *
This block is executed when condition 1 is satisfied
*/
} else if (condition 2) {
/* *
This block is executed when condition 1 is not satisfied and condition 2 is satisfied
*/
} else if (condition 3) {
/* * This block is executed when conditions 1-2 are not satisfied and condition 3 is satisfied */ ...
} else if (condition n) {
/* * This block is only executed when conditions 1-n-1 are not satisfied and condition n is satisfied */
} else {
/* *
This block is executed when none of the above conditions are satisfied
*/
}

Actually, however, this expression is not necessarily correct. In JavaScript, the syntax of an if statement is as follows:

if (condition 1)
// This block is executed when condition 1 is satisfied
else if (condition 2)
// This block is executed when condition 1 is not satisfied and condition 2 is satisfied
else if (condition 3)
// This block is executed when conditions 1-2 are not satisfied and condition 3 is satisfied
...
else if (condition n)
// This block is only executed when conditions 1-n-1 are not satisfied and condition n is satisfied
else
// This block is executed when none of the above conditions are satisfied

In JavaScript, it is given that parts enclosed in curly brackets “{}” are treated as one sentence. Therefore, it is possible to write conditional statements like the ones shown at the beginning. Conversely, the if statement can be written as follows without using curly braces. In this example, if the variable n is an even number, “even number” is displayed, otherwise a message “it is odd number” is displayed.

if (n % 2 == 0)
 alert("Even Number!");
else alert("Odd Number");

Loops

while statement

While statements are used as a control statements for basic repetition. The while statement repeats the process so long as a certain condition is satisfied. The format is as follows.

while (condition)
 When the condition is satisfied, the loop is executed

Of course, you can write as follows.

while (condition) {
 /* *
  &lt;span id="result_box" class="short_text" lang="en" tabindex="-1"&gt;While the condition is satisfied, this block is executed&lt;/span&gt;
 */
}

The format of a while loop is very similar to a simple if statement. In fact, the expression written at the “condition” area of the while loop, is the same as the condition expression used for the if statement.

In the while statement, the condition is first evaluated, and when the condition is satisfied, the block enclosed in curly brackets is executed. Up till this point, the behavior is the same as the if statement. However, when the execution of the block enclosed in curly brackets is completed, instead of executing the closing brace, execution returns to the condition evaluation again. This is repeated until the condition is proven false.

The following is a program that starts a counter from 1 and sequentially displays the value doubled. This process of doubling the value keeps going on until the counter reaches a value of 100.

 

var n = 1;
while (n &lt; 100) {
 alert(n);
 n = n * 2; 
} 


In this program, we first set n to 1 and then enter the while statement. In the while statement, if n is smaller than 100, first display that number in a popup, then double n to prepare for the next round.

When executing the while statement for the first time, n is 1, but at the end of the while block, n is doubled to 2 by the sentence "n = n * 2". Since n is smaller than 2, the block enclosed in curly braces of the while sentence is executed again. After displaying 2, "n = n * 2" is executed again and n becomes 4. After that, the same part is repeated until n reaches 128. When n reaches 128, since the condition of the while statement on the second line is no longer established, the program exits from the block after the while statement.

If you make a mistake in the repeating condition, the same thing will be repeated endlessly, sometimes resulting in a state in which the program does not end. Such a state is expressed as "infinite loop". When it comes to an infinite loop state, the browser may stop responding. In such a case, the browser must be terminated and restarted. When you press three buttons "command" "option" and "esc" on the keyboard at the same time (For MAC),  a "Force Quit Application" screen opens, where you must specify the browser and force quit.

Note that if you open the same page after rebooting the browser, you will also enter the infinite loop, so you must modify the page before opening the page again.

do-while statement

Do-while statements behave similarly to while statements, but where the conditions are evaluated is different. The format of the do-while statement is shown below.

do once and、
&lt;span id="result_box" class="short_text" lang="en" tabindex="-1"&gt;&lt;span class=""&gt;While the condition is satisfied, the statement is repeated&lt;/span&gt;&lt;/span&gt;
while (condition);

See the flowchart below. This is a flow chart of the do-while statement. Compared to the while statement, we see that the part evaluating the condition is processed before the condition is evaluated. Therefore, if you use a do-while statement, it is possible to create a loop where processing is executed at least once.

Do-while statements are not frequently used much as compared to while statements. This is because there are not many situations in which algorithms must be executed at least once.

for statements

When you use iteration, you often use certain variables as counters. A for statement is useful in such a case. The for statement provides such a syntax that it is possible to write three statements for each of the three variables:
A. variable initialization
B. condition
C. counter operation

These would have to be written separately in the while statement, but can be written in one line. See the syntax below; the two bits of code are interchangeable.

Example using a while statement

A.Initialization
while (B.condition) {
/*
* When the condition is satisfied, this block is executed
*/
C.A counter is manipulated;
} 

Example using a for statement

for (A.initialization; B.condition; C.counter change)
This block is executed so long as the condition is satisfied

Writing each one as a concrete example will be as follows. Example using a while statement

 var i = 0;
 while (i &lt; 10) {
  alert("This is repeated。");
  i++; 
 } 

Example using a for statement

for (var i=0; i&lt;10; i++)
 alert("This is repeated"); 

This is to execute the processing block ten times from i = 0 to i = 9. In this example, variables are defined at the same time using var in the "A. initialization" part of the for statement, but this may be done outside the iteration as shown below.

 

var i;
 for (i=0; i&lt;10; i++) { 
/** This block is executed when the condition is satisfied*/
} 

In addition, although there is "C. counter operation" in the for statement syntax, it is also possible to write an assignment statement here. For example, if you want to advance the counter to 0, 2, 4, 6, 8 you can write:

 for (var i=0; i&lt;10; i=i+2)
 {
 /*
  * This block is repeated so long as the condition is satisfied 
  */ 
 } 

"i = i + 2" has the same meaning in "i + = 2".

It is also possible to reduce the counter. If you want to do like 10, 8, 6, 4, 2, write as follows. In this example as well, "i = i - 2" can be rewritten as "i - = 2".

 for (var i=10; i&gt;0; i=i-2) {
 /*
  * This block is executed so long as the condition is satisfied
  */
 }
 

Iteration Control

If you are using repeat, you may want to stop running through the loop at some point, or you may want to go to the next round right now. For such a case JavaScript provides a break statement and a continue statement.

break statement

If you want to stop the iteration halfway, you can escape from iteration regardless of the condition by using the break statement.

See the next program. This program inputs ten characters "male" or "female" and displays the number of times each input was made.

 

 var male = 0;
 var female = 0;
 for (var i=0; i&lt;10; i++) {
  var sex = prompt("Enter Male or Female");
  if (sex == "Male")
   male = male + 1;
  else
   female = female +1;
 } 
alert("Males" + male + " Females: " + female);
 


In this example, you must enter ten characters. How can we stop it in the middle? For example, to input the character string "end", to display the total so far, do as follows.

var male = 0;
var female = 0;
for (var i=0; i&amp;amp;lt;10; i++) {
var sex = prompt("Enter Male or Female");
if (sex == "end")
break;
if (sex == "Male")
male = male + 1;
else
female = female +1;
}
alert("Males: " + male + " Females: " + female);


continue statement


In the above example, if you input a character string other than "man" "end", it will be counted as a female. Here, if you input a character string other than "male", "female" and want to end you need to prevent the counter from an unnecessary increment. To do that, there is a way to set one of the clauses of the if statement to an else if, but you can also do as follows.

 

var male = 0;
var female = 0;
for (var i=0; i&amp;amp;lt;10; i++) {
var sex = prompt("Enter Male or Female");
if (sex == "end")
break;
if (sex != "Male" || sex != "Female")
continue;
if (sex == "Male")
male = male + 1;
else
female = female +1;
}
alert("Males: " + male + " Females: " + female);



In this example, when a character string which is not "male" or "female" is input by using the continue statement, it does not perform the counting operation and enters the next iteration. It should be noted that there is an if statement as well as a continue statement after the sentence that checks whether it is the character string "end" or not.
Conversely, even if the character string "end" is entered, it is neither "man" nor "woman", so it returns to the beginning of the iteration.

Exercise 4-1

Use a while statement to create a program that alerts you to only even numbers "0, 2, 4, 6, 8, 10" among the numbers from 0 to 10.

Exercise 4-2

Use a for statement to create a program that alerts you to odd numbers "1, 3, 5, 7, 9" among the numbers from 0 to 10.

Exercise 4-3


Try N times with the Monte Carlo method and create a program to calculate the Pi. However, let N = 100. In addition, the method of obtaining the circumference ratio by the basic Monte Carlo method is as follows.

Set m to 0.
Point at any point (x, y) in the 1 × 1 range.
If the distance from the origin of the point (SQRT (x 2 + y 2)) is 1 or less, 1 is added to m.
Repeat steps 2-3 N times.
The area of ​​the quarter circle is πr 2/4, and in the above case r = 1, so π can be found with 4 m / N


Exercise 4-4

In the above Monte Carlo method program, make it possible to enter the number of trials from the prompt.


Conditions

Goals


We aim to learn about conditional branching, which changes the program flow according to specific arguments or conditions. Conditional branching is one of the most basic elements in programming. We will also learn about alert() and prompt() as input/output interfaces to an elementary program, and explore Math.random () for generating a random number.

  • Using the prompt() function correctly and enter values ​​into variables.
  • Using the alert() function correctly, you can display messages while using variables.
  • It is possible to create a program using random numbers.
  • You can correctly write a single condition formula.
  • Multiple conditional expressions can be combined using logical operators.
  • Understanding the behavior of an if statement. You will learn to write if statements correctly.
  • Understanding the behavior of if-else statement. You can write if-else statements correctly.
  • Understanding the behavior of the else-if clause. You can write else-if clause correctly.
  • Understanding the behavior of switch statement. You can write switch statements correctly.

Using alert() and prompt()

In the program, it is common to gather input from the user and to issue messages in return. Here, we introduce prompt () and alert () which are the simplest methods of input and output using a browser and JavaScript.

prompt()


The prompt () function is a function that prompts input from the user through a popup window, and returns what the user entered as input to the JavaScript program.

The prompt() gives a pop up window with two elements: a message area which tells the user what to do, and an input area which lets the user type in an input. The prompt() function can put a single value in parentheses (Eg. “Enter one argument (or word)”) and display those values as a message. At the same time, the area for input is displayed, so users may enter a value in the text box provided. The value entered by the user is the value returned by the function.

Note: Since the value is returned as a character string here, caution is required when entering numbers.

In the following example, a popup for entering a value is displayed together with a message “What is your name?” The entered value is stored in the variable yourname.

...
var yourname = prompt("What is your name");
...

alert()

The alert() function is a function for displaying a message using a pop-up window. The alert() function takes one argument and displays its value in a popup as a message. An example of actual usage is shown below.

 

...
alert("Hello World!");
...

In this example, a character string represented by a string literal is simply displayed as a pop-up. On the other hand, you can write expressions in the parentheses of the alert() command. When you write an expression, the evaluated value is displayed as a popup.  

...
var yourname = "taro";
...
alert("Hello " + yourname);
...

 

Examples using prompt() and alert()

The following example is an example using prompt() and alert (). In this example, let’s enter a name on the first line and store the name you entered in the variable yourname. We also display an additional message saying “Hello” to the name entered in the input.

...
var yourname = prompt("What is your name");
alert("Hello, "+yourname);
...

 

The following is an example in which the above program actually operates once a button is pressed. alert("Hello, "yourname);
}


Look at the following program. How does it work?

 

...
var num1 = prompt("Enter the first value");
var num2 = prompt("Enter the second value");
alert(num1 + num2);
...

You may think that the above program stores two different numbers in the variables num1 and num2 respectively, adds both numbers and displays the sum. However, in reality, this is not how it works. We can try this using the buttons created below. Try and see the results for yourself.


As you may have noticed, since the two entered values ​​are treated as character strings instead of numbers, the operator + is interpreted as an addition of character strings, that is, concatenation of character strings into one word. If you want to add numeric values, you need to convert the string to a number. If you use Number () to do the following, it works as expected.

 

...
var str1 = prompt("Enter the first value");
var str2 = prompt("Enter the second value");
var num1 = Number(str1);
var num2 = Number(str2);
alert(num1 + num2);
...

 

An example of the operation is as follows.
var str2 = prompt("2つ目の値を入力してください。");
var num1 = Number(str1);
var num2 = Number(str2);
alert(num1 + num2);
}


Random Numbers

What are Random Numbers?


A program describes the various processing activities to be performed by the computer. Basically, program operation is determined by describing that the operation has changed depending on some condition, lest the same process is repeated or looped. However, some algorithms require randomly chosen values ​​(random numbers) like the Monte Carlo method. Many programming languages ​​have functions for generating such random numbers.

Math.random()

To generate random numbers in JavaScript, use Math.random (). Math.random () is a call to the random () method of the Math object, but the Math object is described elsewhere. There is no need to write all the code behind the Math object, it is already written for you to use.

When called, Math.random () returns a number greater than or equal to 0 and less than 1. What value will come back will be different depending on the time.

For example, see the following program. In this program, Math.random () is called, the return value is assigned to the variable num, and its value is displayed on the next line. Press the button of the operation example several times to see that different values ​​are displayed each time you press the button.

var num = Math.random();
alert("The random number is " + num)

}


 

Overview of Conditional Branching


When you write a program, you may want to change the behavior of the program depending on the input value etc. Conditional branching is what realizes such a function. In JavaScript, an if statement and a switch statement are prepared for conditional branching.

 

Conditional Expressions

Comparison Operations

In order to change the behavior of the program depending on the condition, it is necessary to memorize the method for describing conditional statements.

In many programming languages, there is a kind of operation that returns whether an expression is true or false. In other words, one can also use operators to describe conditions.

 

Operator Meaning Example
== Equality operator. It compares the left and right values. Returns true if they are the same, false otherwise. a == b、sum == 100
!= Inequality operator. Whether the left and right values are the same is judged. Returns true if they are different, false if otherwise. a != b、sum != 100
< It judges whether the value on the left is lesser than the value on the right. Returns true if it is small, false if otherwise. a < b、sum < 100
> It judges whether the value on the left is greater than the value on the right. Returns true if it is small, false if otherwise. a > b、sum > 100
<= It judges whether the value on the left is lesser than or equal the value on the right. Returns true if it is less than or equal, false if otherwise. a <= b、sum <= 100
>= It judges whether the value on the left is greater than or equal to the value on the right. Returns true if it is greater than or equal, false if otherwise. a >= b、sum >= 100

 

String Comparison

You can also use comparison operators in strings. In this case a little caution is necessary. When comparing the size of character strings, they are compared in alphabetical order. Therefore, “3” <“5″ , ” 12 “<” 3 ” , ” abc “<” def ” are all true. However, in the case of Japanese, it is a little more complicated. Within the computer, characters are represented by numbers called character codes (there are multiple codes such as JIS, EUC, Unicode). Characters are determined by the order of this character code, not according to alphabetical order.

Logical Operators

In order to describe more complicated conditions, it is necessary to combine several conditions. For example, if you want to describe a condition that a number num is greater than 3 and less than 10, you must satisfy two conditions: 3 <num and num <10. In such a case, there is what is called a logical operator to combine expressions. The logical operators are listed below.

 

Symbol Meaning Example Explanation
&& Logical AND. and operation. It becomes true when both the left and right are true. 3 < num && num < 10 num is greater than 3 and less than 10
|| Logical OR. or operation. True if either or both of the left and right are true. num < 3 || 10 < num num is greater than 3 or less than 10
! denial. not operation. Returns false if the value to evaluate is true, true if false. !(num < 3) num is not less than 3

 

If you want to describe a condition that a certain number num is larger than 3 and smaller than 10, write “3 <num && num <10” using the above logical product. You can not write like “3 <num <10”, so you need to be careful.

There is also a priority in logical operations as arithmetic operations such as sum-difference product quotient have priorities. Priorities of logical operations are “!”, “&&”, “||” in descending order of priority.

Logical operations have various features. For example, denial of negation is affirmative. Using logical operation “[comparison operation]” is the same as “!! [comparison operation]”. “Below” means “not greater than”. There is also a famous law called “de Morgan’s law” in the logical operation. Among them, “! ([Comparison operation 1] && [comparison calculation 2])” guarantees that it is the same as “! [Comparison operation 1] ||! [Comparison operation 2]”. Similarly, “! ([Comparison operation 1] ∥ [comparison operation 2])” is the same as “! [Comparison operation 1] &&! [Comparison calculation 2]”.

if statements、if-else statements

Basic if-statement

The use of the most basic if statement is to execute a part of the program only when a certain condition holds. What is shown in the following figure is called a flowchart, and it is one of methods for expressing the program flow. In this figure, the flow of an if statement is shown. In the if statement, processing is performed only when a certain condition is satisfied, and the most basic way of writing it is to do nothing if it does not hold.

 

 

The if statement which behaves like the above figure is expressed as follows. In the parentheses of the condition of the if statement, a conditional expression describing combinations of comparison operators and logical operators as described above is written.

If the condition expression seems to return a true value, the part enclosed in curly brackets is executed. When the conditional expression does not hold, that is, when it becomes false, it will not be executed in the curly brackets and will proceed to the next command.

 

if (condition) {
/* *
Processing block executed only when the condition is satisfied
*/
}

 

The else clause of the if statement

In the above basic if statement, the block enclosed in curly brackets was executed only when the condition was satisfied. However, when writing various programs, there are cases where you want to execute process 1 if the condition is satisfied and process 2 if it is not. It is possible to write the reverse conditional statement using the logical operator ‘!’ And execute the process 2, but it is unlikely to be a wise way. In order to meet such needs, the if statement in JavaScript can be written as an else clause. The notation when using the else clause is as follows.  
if (condition) {
/* *
Processing block executed only when the condition is satisfied
*/
} else {
/* *
* Processing block executed only when the if condition is not
* satisfied
*/
}

It is shown in the flowchart as follows.

else if

It is also possible to specify more detailed conditions using an if statement. “○ ○ ○ when it is ○ ○, △△△ when not △ △, □□□ when not □ □, □□□ when not □ □,  □ ○ will be executed”. In order to describe such a conditional branch, conditions are confirmed in sequential order from top to bottom, and only the ones that apply first are executed. If a certain condition 1(ex: num <10) applies exactly to another condition 2 (eg num <100), condition 1 will never be executed unless it is  is written first.  
if (condition 1) {
/* *
* Processing block executed only when condition 1 is
* satisfied
*/
}
else if (condition 2) {
/* *
* Processing block executed only when condition 1 is not satisfied
* and condition 2 is satisfied
*/
} else if (condition 3) {
/* *
* Processing block executed only when condition 1 to condition 2
* are not satisfied and condition 3 is satisfied
*/
...
} else if (condition n) {
/* *
* Processing block executed only when condition 1 to condition n-1 * are not satisfied and condition n is satisfied
*/
}

You can join any number of else if statements. Also, at the end, if you wish to include the part of “execute ○ ○ if none of the conditions are met”, do as follows.  

if (condition 1) {
/* *
* Processing block executed only when condition 1 is
* satisfied
*/
} else if (condition 2) {
/* *
* Processing block executed only when condition 1 is not satisfied
* and condition 2 is satisfied
*/
} else if (condition 3) {
/* *
* Processing block executed only when condition 1 to condition 2
* are not satisfied and condition n is satisfied
*/
...
} else if (condition n) {
/* *
* Processing block executed only when condition 1 to condition n-1
* are not satisfied and condition n is satisfied
*/
} else {
/* *
* Processing block executed only if none of the conditions
* apply
*/
}

 

Example of a program using an if statement

Let’s see an example of an actual program using an if statement. See the program below. When you press the button in the HTML part, the part that jumps to the function is already mentioned. In JavaScript, the second line prompts input from the user and stores the value in the variable str. Since the value stored in the variable str is handled as a character string here, it is converted to a numerical value using Number () on the next line, and it is stored in the variable num again. Moreover, we branch from line 5 using an if statement. In line 5, we check whether the value num input to the form is 2 and whether the remainder is 0 or not. That is, we check whether num is a multiple of 2 or not. If it is a multiple of 2, it executes in the immediately following block. That is, a message “It is a multiple of 2” is displayed. If it is not a multiple of 2, jump to the else if line 8. Here, we check whether num is a multiple of 3 or not. In the case of a multiple of 3, as in the case of multiples of 2, execute the subsequent block and display the message “It is a multiple of 3”. If it is neither a multiple of 2 nor a multiple of 3, it jumps to the last else clause and displays the message “It is neither a multiple of 2 nor a multiple of 3”. HTML part
<button onclick="iftest()">Example using statements</button>. 

JavaScript part

function iftest() {

 var str = prompt("Enter a number");
 var num = Number(str);

 if (num % 2 == 0) {
  // Alert for 2 alert("The number is divisible by 2");
 } else if (num % 3 == 0) {
  // Alert for 3 alert("The number is divisible by 3");
 } else {
  // If indivisible by either
  alert("The number is neither divisible by 2 nor 3");
 }

} 


In the above program, what will happen if you enter a number that is a multiple of 2 or a multiple of 3, such as “6” or “12”? Will both “both being multiples of 2” and “being a multiple of 3” be displayed? Recall that the program basically runs from top to bottom. When “6” or “12” is input, it is evaluated first by the if statement of the fifth line. Since “6” and “12” are multiples of 2, the conditional expression of this if statement is satisfied and the message “is a multiple of 2” is displayed. Once it matches the condition, the else if and else after that will be skipped. Therefore, when a numerical value that is a multiple of 2 or a multiple of 3 such as “6” or “12” is input, only the message “It is a multiple of 2” is displayed.

switch statements

The mechanism for conditional branching of JavaScript is a switch statement. The switch statement is a control portion that branches to multiple options according to what value the evaluation result of the expression takes. It is convenient to branch into multiple choices depending on the evaluation result of the same expression, because it can be described easily from the if statement. Conversely, a conditional branch that can be written with a switch statement is complicated, but it can also be written in an if statement.

Next is an example using a switch statement. In this example, the user inputs either “morning”, “daytime”, “evening”, or “night”, and the words of greeting are changed by inputting.

If the value of the expression in the parentheses of the switch statement matches one of the values ​​after the multiple case clause, the function is executed from the alert () function on the next line.

When a break statement appears in execution, the switch statement ends. If there is no break statement, it will be executed as it is until the following  case clause. For example, in the example below, if you type “evening”, the part under the next “case” night “is executed as it is.

Also, if it does not match any case clause, it is executed from the line following the default clause.

var word = prompt("Type Morning/Afternoon/Evening/Night for the time");
switch (word) {
case "Morning":
alert("Good Mordning。");
break;
case "Afternoon":
alert("Good Afternoon");
break;
case "Night":
case "Evening":
alert("Good Evening。");
break;
default:
alert("We cannot understand");
}


Exercise 3-1


Create a button so that the message
“What is the weather like today?” is displayed. Accept inputs for “Sunny”, “Rainy”, “Windy”, “Snowy” and “Cloudy”. When the user inputs “Sunny”, display the message “Have a wonderful day!”. Think of appropriate messages for other weather conditions. If the user inputs anything other than the predetermined weather conditions then ask the user to try again.

Exercise 3-2

Create a fortune teller program using the Math.random() function in JavaScript. If the number is less than 0.1, display “Bad Luck”, if it is between 0.1 and 0.33 display “Some Luck”, if it is between 0.33 and 0.66, display “Good Luck”, and if it is between 0.66 and 1 display “Amazing Luck!”. Use alerts to display your messages.

Exercise 3-3


Create two buttons, one for a conditional branch with an if-else statement and one for a switch-case statement for the following program.

When you press a button, the prompt “Please answer the what dinner you would like today using one of the keywords: Western / Japanese / Chinese / Other” is displayed, and according to each input, recommended restaurants are displayed in an alert.

Exercise 3-4


When you press a button, the prompt “What day of the week?” Is displayed, and when you enter the day of the week, the prompt “Period?” is displayed next. When you enter the period, the subject you are taking is shown using an alert.

Create a program to do this. However, if you enter a day of the week that does not have any classes display an alert “No Class!”.

JavaScript basics and Event model

Goals

Learn basic concepts of JavaScript, concepts such as variables, expressions, sentences and so on. Also learn about the relationship between web pages and JavaScript.

  • Understanding how to use the script element. Also understand the three ways of writing JavaScript programs.
  • Understanding constants, variables, and expressions.
  • Understanding sentences.
  • Understanding functions without arguments.
  • Understanding the mechanism by which programs written in JavaScript are executed.
  • Understanding events.
  • Understanding how to write event handlers.
  • Understand some fundamental functions such as alert().

 

Basics of JavaScript

Execution of the program

Like many programming languages, JavaScript programs are composed of sentences and declarations that are executed from the top to the bottom. A sentence is line of code where one changes the value stored in the memory, or controls the flow of the program. A declaration defines a function, which is essentially a chunk of commands waiting to be processed. In the declaration, only defining the function, neither actually changes the value stored in the memory nor does the calculation. It is only when the function is called that it actually changes or stores the value stored in the memory. More details will be explained later on in this lesson.

Before describing the process of actually changing the value stored in the memory, the concept of values themselves and expressions using them will be explained.

 

Data Types

In JavaScript, in order to store data, the following seven types of data (types) are specified. All values belong to one of these types.

Undefined Type
A type used when no value is assigned to a variable. Only an undefined value is specified as a value.
Null Type
As the value, only null representing an empty state is specified.
Boolean Type
A type for representing truth or falsehood. Two values, true and false, are specified as values.
String Type
A type for representing a string.
Symbol Types (Special Characters)
A type used for object properties and others. It is used to represent a special value that cannot make two or more same values.
Number Types
A type for representing a numeric value. It can express both integer and real number.
Object Types
An amalgam composed of a combination of the above six types.

Constants and Literals

In JavaScript, it is possible to handle the seven types mentioned above as data, and there is a way of writing to describe the value (constant) in each. This style of writing is called a literal. Here we introduce literals of each constant.

Undefined Type’s Value
For undefined type values only undefined is prescribed, and values can be represented as “undefined” as they are. However, undefined is not a literal.
Null Literal
As the value of the Null type, only null is specified, and the literal is also “null“. Care must be taken because initials must be lowercase.
Boolean Literal
The true and false values are described as “true” and “false“, respectively.
String Literal
It is described by enclosing a character string with single quotation mark (‘) or double quotation mark (“), but if you put a single quotation mark enclosed in another single quotation mark, or double quotation marks enclosed in double quotation marks, Prefix the character with a slash (\).
Example: 'Keio University', 'Keio University', '12345', 'I' m a student. ',' I \ 'm a student.'
Symbol Type’s Value
There is no literal to handle the value of Symbol type directly. By using the function Symbol () you can create a value of Symbol type.
Number Type’s Value
There are integer literals representing integers and floating point number literals representing real numbers.
In addition to the integer literal, there is a method of expressing it in decimal notation (beginning with a number with a non-zero head like 1 or 23), a method of expressing in binary notation (head starts with 0 b like 0 b 1 and 0 b 10111) , A method of expressing it in hexadecimal notation (the head starts with 0x as 0x1 or 0x17) and the like.
On the other hand, there are also methods for expressing floating point number literals using general expressions such as 3.14159, and expressing using e as in 6.022e23 (in this example, representing 6.022 × 1023).
Object Literal
It is a combination of multiple values and uses expressions such as {“key 1”: “value 1”, “key 2”, “value 2”, …}. In addition to string literals, you can use arbitrary literals for “value 1” and “value 2”.

Variables

A variable is one in which a place is prepared in the storage area of the computer and a name is given to the place. A variable can contain a value. Depending on the language, there are variables whose usage is limited, such as variables that can only contain numbers, variables that can only contain letters, but in JavaScript anything can be in the same variable.

変数の概念
変数の概念

The program describes the processing procedure when data is processed according to a certain algorithm.

It is like writing a recipe for cooking, and in the case of “stir-fried food”, you cut the ingredients and use oil to grease the frying pan. At  some point in time, if the ingredients are  cabbage / carrot / onion it is time to stir the vegetables, if the ingredients are green peppers / pork / bamboo shoots,  then it is time to make sauce.

Here, what can be done by something “ingredients” will be different. In other words, in the recipe you have to write “cut something, stir something, taste something”. This “something” is a variable. It is the same in addition. Write “c = a + b”, “a” is 3, “b” is 5, “c” is 8. In this way, values ​​are represented by symbols. Note that here, unlike “c = a + b” in mathematics, JavaScript implies substituting the result of “a + b” for the variable “c”.

Variable Declaration

In JavaScript, what is called a declaration statement is prepared to clarify that “this symbol is a variable”. To clearly declare variables in JavaScript, do as follows.

var varname;
var varname = initial value;

The first method is simply declaring that you prepare a variable and name it “varname”. Nothing happens explicitly. Even if you attempt to display the value using the debugger here, since the value is not defined, it becomes “undefined”. In the second method, a variable named “varname” is prepared and an initial value is assigned to it. The initial value part may be a constant such as a number, a character, a character string, or an expression that generates a calculation formula or an object.

It is also possible to declare and initialize variables on separate lines. For example, if you divide the second method above into two lines, it becomes as follows.

var varname;
varname = initial value;

Actually, in JavaScript, the program operates without explicitly declaring variables. However, since such usage often causes problems, it is better to make variable declarations.

Naming Variables

There are rules on how to name variables. When attaching a variable name, it is necessary to observe the following rules.

  • Allowed characters are alphanumeric characters, underscore (_), dollar sign ($)
  • The first character is non-numeric
  • Capital letters and lower case letters are distinguished
  • Reserved words cannot be used

A reserved word refers to a word already used for other purposes in the language. For JavaScript, reserved words are as follows.

break, case, catch, continue, default, delete, do, else, finally, for, function, if, in, instanceof, new, return, switch, this, throw, try, typeof, var, void, while, with

Also, it is better not to use the window object property as a variable name. For example, name is included as a window object property so it cannot be used.

When attaching a variable name, it makes it easier to understand the program by showing the meaning of the variable. For example, you may name the variable storing the total as “sum”, or name the variable nickname as “nickname”. However, one must be careful that the names are not too long.

There are various ways of assigning variables. For example, Camel Case, Hungarian Notation, Google JavaScript Style, etc. If you are watching examples of various sites, you notice that programs are written in the same way. Although it is not necessarily required to decide variable names and function names according to this style, it is helpful to refer to it as it helps to write a clean and easy-to-read program.

 

Scope of variable

If you do not declare variables as shown above, it may cause several problems. What is the problem? Many programming languages ​​have a concept called “scope”. This is to allow names to be used only in certain places in order to avoid confusion.

For example, variables with common names such as “date” and “sum” may already be used in many programs, and if you use these names too often, it can cause problems. Attempting to save to a variable of the same name as one that exists elsewhere can cause confusion. Therefore, the idea of ​​the scope is to limit the range in which the name becomes effective to only a specific part of the program.

The following program shows an example where such a confusion occurs. Here, alert () is a function for pop-up displaying a message. In this example, the value in the variable word is displayed.

var word = "Hello";

// hello 1
function hello1() {
var word = "Good Evening";
alert(word);
}

// hello 2
function hello2() {
alert(word);
}

// hello 3
function hello3() {
word= "Good Evening";
alert(word);
}

// hello 4
function hello4() {
{
var word = "Good Evening";
}
alert(word);
}
<button onclick="hello1()">hello1</button>
<button onclick="hello2()">hello2</button>
<button onclick="hello3()">hello3</button>
<button onclick="hello4()">hello4</button>

Actual movements are as follows. Let’s press the button. What is going on? Since the movement also changes according to the order in which buttons are pressed, try to grasp the movement by making full use of the browser’s reload functions. It might help to use a debugger.





When you press the hello 1 button, “Good evening” is displayed. This is indicated by alert () on line 6. The display content is the value of the variable word declared in the fifth line immediately above.

Initially, when you press the hello 2 button, “Hello” is displayed. This is an alert issued in the sentence on the 11th line. The value is initialized in the first row. Notice that the value assigned in the assignment statement on line 5 is not displayed here. Why is the assignment statement on line 5 irrelevant? According to the rule “program runs basically from top to bottom”, there is an assignment statement on line 5 before alert () on line 11, so the value of word should be “good evening”. However, the fourth to the seventh lines are function declarations. The part that is a declaration will not be executed until it is actually called from another function. Therefore, the value of the variable word is never changed.

However, with this explanation, once you press the hello 2 button after pressing the hello 1 button, you should see “Good evening”. However, in fact, even if you press the hello 2 button after pressing the hello 1 button, “Hello” is displayed. Actually, in this program, the word variable declared in the first line and the word variable declared in the fifth line are different things. This concept is what is known as scope.

JavaScript has two types of scope called global scope and local scope. Scope defines the range that variables and functions can be referred to, and in the case of global scope it can be referenced from anywhere in the program. On the other hand, in the case of the local scope, it is limited to within the function, and can only be referenced in the function.

In the above example, the word variable in the first line is defined as a global variable (global scope variable), and the fifth line word variable is defined as a local variable (variable that can be referred to only from the lec 01 _ 01 _hello 2 function). Therefore, from the lec01_01_hello2 function, you can access the word variable declared in the first line, but you cannot access the word variable in lec01_01_hello1. Conversely, referring to the word variable from lec 01 _ 01 _hello 1, the local variable is referenced and the global variable can not be accessed.

Declaring local variables is possible by declaring them using “var” in the function. When declared outside the function, it becomes a global variable like the declaration of the first line. What’s confusing is that if you do not declare with “var” in the function, that variable will be treated as a global variable. Extreme caution is required when using global variables. In the example above, press the hello 3 button and then press the hello 2 button.
“Good evening” is displayed. This is an example that affects the lec 01 _ 01 _hello 2 () function because it rewrites the contents of the word variable which is a global variable in the lec 01 _ 01 _hello 3 () function. If you use global variables, you should be careful not to confuse them with other variables naming variables.

This program gives an easy name “word”, but if you use such an easy name unexpectedly you see from other places, when you use it in combination with another program there may be a clash between the names used.

Hello 4 button is a trap that is often a mistake made by a person who has learned another language such as C language. JavaScript has only global scope and function local scope.
Therefore, even if you create a new block like the lec01_01_hello4 () function, it will be a local variable in the function, so you need to be careful. Those who learn programming for the first time, please be aware that there are programming languages ​​that can explicitly create different scopes by creating new blocks like this.

Expressions

We now come to the concept of “expressions” in a programming language. In terms of mathematical expression, we think of something like y = 2x + 3, but the concept of expressions in programming is somewhat different. An expression in programming is “to evaluate (calculate) and generate a value”. For example, “1” is also an expression and “hello, world” is also an expression. The former generates a value of 1 as a value, while the latter generates a character string “hello, world” as a value.

The expression “evaluate” the expression does not mean what it does in mathematics. In programing lingo, expressions do not necessarily perform arithmetic operations. For example, as we have seen, there are expressions that generate character strings and even values such as true and false. They can answer yes (true, true) or no (false, false) on a condition such as a “variable n is smaller than 3”.

Some functions, when called, do not generate values. Therefore, when we say “to evaluate” we need to say it without implying that we are “doing calculations”. An evaluation refers to obtaining expressions by executing expressions and functions using variables and constants.

An expression is made up of operators and operands. Operators are symbols for manipulating values ​​such as + and -. Also, the operands are objects that are manipulated by operators. For example, in “1 + 2”, 1 and 2 are operands and + is an operator. The result of this expression is 3.

Many programming languages, not just JavaScript, have many operators. These can be categorized by the number of operands that are present in the expression.
For example, the + operator takes one operand on each of its right and left.This is called a binary operator. There are also one-term or unary and three-term or ternary operators.
For example, the symbol used in “-3” representing a negative number is a unary operator.

Arithmetic Operations

First, let’s look at arithmetic operations as basic and understandable expressions.
Arithmetic operations include, the following operators.

Operator Meaning Example
+ Adds left and right values 1+2、1024+2048
Subtracts the right value from the left value 5-3、2048-1024
* Multiplies the left and right values 1*2、1024*2048
/ Divide left value by right value 6/3、2024/128
% Find the remainder when dividing left value by right value 100%30、29%2
++ Increment (add 1 to the value). The added value is set to the variable specified by the operand. ++i、j++
−− Decrement (Subtract value by 1). The added value is set to the variable specified by the operand. −−i、j−−

For the four operators “+”, “-“, “*” and “/”, it is an ordinary four-arithmetic operation, so you do not need to explain it. “%” may not be used much in everyday life, but it is an operation that returns the remainder. For example, if it is 100/30, the remainder is 10, so the expression 100% 30 returns 10. Also, in the JavaScript “%” operation, decimals are passed on to the remainder. For example, the result of 100.5% 30 is 10.5.

“++” and “-” may be more confusing. This is an operator that affects the values ​​in variables, and writing “++ i” will increment the value in i by 1 and return that value. For example, if i is 5, writing “++ i” will return 6, and the value of i itself is replaced with 6.

What’s more confusing is that the values are different when you write “++ i” and “i ++”.
When “++ i” is described, the value is increased by 1 before returning the value. However, when writing “i ++”, the value in the variable is incremented by 1 after the value is returned.

When the value of i is 5, writing “++ i” will return both the value to be returned and the contents of i to 6, but if you write “i ++”, the value returned is 5, but the value of i is 6.
By describing an expression such as “j = i ++” and confirming the values ​​of i and j, the behavior can be understood.

String operations

Strings also have operators.
For example:

Operator Meaning Example
+ Concatenation. It concatenates the left and right values to generate one character string. "hello, " + "world""My name is" + firstname

There are things to be careful when computing character strings. For example, “5 + 4 +” 3 “” is a case where a character string and a number are mixed in the same expression.
The “+” operator is used for both concatenation and arithmetic operation.

In the case of “5 + 4 +” 3 “”, since the operation is evaluated from the left side, it is expressed as “(5 + 4) +” 3 “” in parentheses.
For this reason, “5 + 4” is executed first to become “9”, which is converted to “9” “of the character string so as to be connected with the character string” 3 “”,  eventually to “93” “.

As you can see, numeric type objects are automatically converted into characters at the time the character string appears, and it becomes a character string calculation, so care must be taken.

Assignment operator

An assignment operator is slightly different from the operator described so far. Actually, you may have used assignment operators many times so far. An assignment statement is basically one that puts a value in a variable. Actually, in JavaScript, ‘=’ is used for value substitution and is also treated as a kind of operator.

Other assignment operators are described below.

 

Operator Meaning Example
= Substitution. Assigns the value on the right to the variable on the left. a = 1、a = b、a = 3 + 4
+= Adds the value on the right to the variable on the left. a += 1、a += b、a += 3 + 4
-= Subtracts the value on the right from the variable on the left. a -= 1、a -= b、a -= 3 + 4
*= Multiplies the value on the right by the variable on the left and substitutes the result on the left side. a *= 1、a *= b、a *= 3 + 4
/= The right variable divides the left variable and assigns the result to the left side. a /= 1、a /= b、a /= 3 + 4
%= Divides the variable on the left with the value on the right and assign the remainder to the variable on the left. a %= 1、a %= b、a %= 3 + 4

When assignment operators are used, attention must be paid that the left side of the assignment operator is always a variable.

Operator precedence

In mathematics, multiplication and division are stronger than addition and subtraction, and the answer of “1 + 2 * 3” is not 9 but 7. Javascript also has the concept of strength and precedence.
The rules for precedence are shown n below.

Strength of Precedence Operator
Strong ( )
++、−−、−
*、/、%
+、−
Weak =、+=、-=、*=、/=、%=

For example, “a% = 3 + 4” is obtained by substituting a remainder obtained by dividing a by 7, substituting a obtained by dividing a by 3 into a, adding 4 to it, and adding 4 to the value of the expression It does not become.

As you can see from the above, it is “bracket ()” that has the strongest bond.
If you want to change the order of the join, you can enclose the part you wish to enhance coupling in parentheses.
Even if you do not necessarily want to strengthen the connection, making parentheses easier to understand misleading expressions is effective for preventing program mistakes

Statements and declaration

A JavaScript program consists of “statement” and “declaration”. We will briefly explain what a “statement” and “declaration” are.

Statements

A “Statement” is the basic unit of processing and represents some procedure.
It may also be used to control the flow of procedures in a program.

In JavaScript, there are many kinds of statements.  An expression statement (one in which expressions are treated as single statements, in many cases with assignment operators), a control statements (accurately classified into if statements, switch-case statements, etc.), and a return statement are all the fundamental types of statements in JavaScript. Combining these statements makes it possible to describe a series of procedures.

Declaration

A “Declaration” is a procedure that makes things visible from other parts of the program, and nothing happens when that part is executed.

It is effective only when it is instructed to actually be executed from other parts of the program. This is equivalent to a function declaration.

Incorporating a JavaScript program in the Website

script elements and JavaScript

Of course, in order to connect HTML (Web page) and JavaScript programs, some mechanism is necessary. For this purpose, HTML has the “script element”. The script element is an element used when inserting a program into HTML. In fact there are two ways of writing it as shown below.

Let’s write a program directly in the script element.

...
<script type="text/javascript"><br />
  var a=1;<br />
  var b=2;<br />
  alert(a + "+" + b + " = " + 3);<br />
</script>
...
How to write the path to the program file in the attribute of the script element

...
<script type="text/javascript" src="example.js"></script>
...

The former method is easy to use when the program is short, the latter method is easy to use when the program size is large to some extent.

Executing JavaScript

Basically, when loading HTML, the Web browser processes each statement in order from the top to bottom. At this time, if there is a script element in processing, the JavaScript program is executed at that timing.

However, when a function is declared within JavaScript, it is only executed once it is called. For programs outside the function declaration, they are executed when they are read.

Also, when manipulating HTML elements from JavaScript, it is necessary to note that elements of HTML must be created at the time the JavaScript program is executed.

Here, you may wonder where the script element is located. Generally, either of the following two methods are adopted. One way is to put the script element in the head element and the other is to put it at the end of the body element.

Event Model

One of the cooperation between HTML and JavaScript is event handling. Here, an event generated by a Web page and its handling method will be described.

HTML elements and events

A page expressed in HTML generates an event to the Web browser the moment it is displayed.
Events include those caused by user operations such as click (onclick) and double click (ondblclick) on elements such as buttons, as well as those occurring at the end of page loading, moving to another page, and the like. The types of events generated by the Web browser are shown below.

Examples of major events are shown below.

Type Event Events Explained
Page Events onload When a page has fully loaded
onunload When moving to another page, or when the page is closed
onresize When the size of the page has changed
onscroll When a user scrolls through the page
Mouse Events onclick When the user clicks the mouse
ondblclick When the user double clicks the mouse
onmousedown When the moue is pressed down
onmouseup When the mouse is released
onmouseover When the mouse hovers over a region or element
onmouseout When the mouse hovers out of a region or element
Keyboard Events onkeydown When a keyboard key is pressed down
onkeypress When a keyboard key is pressed
onkeyup When a keyboard key is released
Form Events onchange When there is a change in the form elements
onsubmit When the submit button is clicked
onreset When the reset button is clicked
Focus Events onfocus When an element or region is in focus
onblur When an element or region is out of focus

Invoking a function by an event

In HTML + JavaScript, JavaScript programs are often activated by events. A program associated with such an event is called an event handler. In many cases, the JavaScript event handler is defined as a function, and the program is executed by calling the function.

When the button is clicked, an HTML and JavaScript program displaying an alert is shown below

 

HTML
...
<button onclick="message();">Click me!</button>
...
JavaScript
function message() {
alert("The button has been pressed");
}

The following buttons can be realized by the above HTML and program.


In this JavaScript program, the first line to the third line declares a function named “message”. The contents of the function is only from line 1 to 2, and is only displaying an alert. Also, in the HTML, we call the “message () function” when “onclick” event occurs.
That is, it defines an event handler for “onclick” event.

Please note that the event handler described in HTML is the JavaScript program itself.
You can write JavaScript programs in the ‘message ();’ part only. Therefore, it is possible to call “alert () function directly.


Such an example is shown below. This description method also operates in the same way as above, but if complicated pr
ocessing is performed when an event occurs, it is easier to read the program by calling it after declaring the function.

...
<button onclick="alert(&quot;The button was pressed&quot;);">Click me!</button>
...

Practice Exercise 2-

Write a program (function) in the script element and create a program to display “Hello” with an alert when the button is clicked.


Practice Exercise 2-

Write a program to an external file and read it with the script element. When you press the button, create a program to display with “Hello” as an alert.

Practice Exercise 2-

Create a program that makes a variable “0”, “increase by 1”, “decrease by 1”, “times 2”, “1/2”, and when each button is pressed, it performs its operation and displays the result as an alert. Set the initial value of the variable to 0.