How to immediately make learning JavaScript more fun

How to immediately make learning JavaScript more fun
0.0 0

#1

One big strength of JavaScript is that one can make something that works with minimal learning.

What is necessary:

This code puts an input field on the page:

<input id="yourInput">
<button type="button" onclick="yourFunction()">Submit</button>
<p id="yourOutput"></p>
Script:
function yourFunction() {
  var x = document.getElementById("yourInput").value;
  text = x + 2;
  document.getElementById("yourOutput").innerHTML = text;
}

Pressing the button calls the function yourFunction().

The function first assigns what was in the page element with yourInput id, which in this example is the text written into the input field to a variable x.

Next, the text variable gets assigned a result of addition of x + 2.

Finally the function assigns the value of the text variable to the page element with yourOutput id. In this example, it displays result of the addition in that paragraph.

Script needs to be put either in the page <head> between <script></script> tags or in a separate file like script.js which would need a <script src="script.js"></script> tag for a script file put in the same folder as the .html page.

Example page:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Script Demonstration</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen" href="style.css" />
    <script>
     function yourFunction() {
       var x = document.getElementById("yourInput").value;
       text = x + 2;
       document.getElementById("yourOutput").innerHTML = text;
     }
    </script>
</head>
<body>
    <p>Adds 2 to input.</p>
      <input id="yourInput">
      <button type="button" onclick="yourFunction()">Submit</button>
      <p id="yourOutput"></p>
</body>
</html>

Result:
Zrzut%20ekranu%20z%202018-07-12%2011-19-12

Basing on this and stuff taught in the Basic JavaScript course it’s possible to make various tools, for example one converting metric to imperial unit and reverse.
When making such tools, one encounters a variety of problems that get solved using knowledge from the course and other sources.

For example, in Firefox, inputing 40 results in this:
Zrzut%20ekranu%20z%202018-07-12%2011-45-40
instead of this:

Zrzut%20ekranu%20z%202018-07-12%2011-37-51

It’s because apparently the variable is interpreted to be text when taking value from the input field. So, it needs to be converted by using Number() function. Like this text = Number(x) + 2;


#2

Ugh, it wasn’t supposed to be posted yet.

EDIT:
Finished. For some reason pressing space twice very fast posts a post O_o .