JavaScript

JavaScript is a programming language made to change the appearance or behaviour of a web site. In terms of storytelling we can see JavaScript as the actions happening on our web site (story). JavaScript code is stored in plain text files with the file ending .js or included into an HTML file with the <script> tag. For the latter it’s recommended to insert the script at the bottom of the page, above the closing </body> tag.

JavaScript is executed through the browser. You can test code snippets through the inspector tool or with a sandbox like JSFiddle.

We’ll inspect that with the work Do It by James Bridle (2020). Caution: Flicker.

We’ll start with creating a button that will change it’s color when we click on it.

A search for “JavaScript random number” reveals for example this page.

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>(Java)Scripted Story</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

    <div id="div-1" class="prevent-select" onclick="random_color();">1</div>

    <script type="text/javascript">
        function random_color() {
            // Get 3 random color values and convert them to string
            var r = Math.floor(Math.random() * 256).toString();
            var g = Math.floor(Math.random() * 256).toString();
            var b = Math.floor(Math.random() * 256).toString();

            // Change the color of the div
            document.getElementById('div-1').style.background = 
            'rgb(' + r + ',' + g + ',' + b + ')';
        }
    </script>

</body>
</html>

css/style.css

div {
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
}

div:hover {
    cursor: pointer;
}

#div-1 {
    height: 10vh;
    width: 5vw;
    background-color: orchid;
    position: fixed;
    top: 5vw;
    left: 5vw;
}

.prevent-select {
  -webkit-user-select: none; /* Safari */
  -ms-user-select: none; /* IE 10 and IE 11 */
  user-select: none; /* Standard syntax */
}

Functions

On click onto the colored div will change its color. The function is called through onclick="change_color();". The function is defined through function change_color() { ... }. The word function is a reserved keyword, the name of the function itself is of your choice. Everything inside the {} will be executed when the function is called.

// Syntax of a function:
function my_function() {
    // Code of the function.
    // Code of the function.
}

The block of code to be executed inside the function is indent by a tab. This is done for (human) readability only. It’s possible to place all the code in one line.

Variables

The next keyword var defines a variable. A variable can store data (and functions) and this data can change over time. With the help of the built-in random function (Math.floor(Math.random() * 256);) a number between 0 and 255 is generated and assigned to the variables r, g and b.

This values are converted into a string (text) with the function toString() and then a string is concated with these values. The syntax of the string follows the CSS command for an rgb value.

With document.getElementById('div-1').style.background =              'rgb(' + r + ',' + g + ',' + b + ')'; this rgb values will be assigned to the HTML element with the id “div-1”.

Data Types

Numbers and strings are two different primitive data types. (We’ll learn more later.)

We can insert numbers into a string with a more sophisticated method than the one we’ve used above. It’s called string formatting.

    <script type="text/javascript">
        function random_color() {
            // Get 3 random color values
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);

            // Combine them as a string with string formatting
            var color = `rgb(${r}, ${g}, ${b})`;

            // Change the color of the div
            document.getElementById('div-1').style.background = color;
        }
    </script>

Passing arguments to functions

Next we’ll create a second div and change it’s color as well on click.

As we want to use the same function for both divs, we have to make it variable. We can pass arguments to a function via the (). In the code below the ids of the elements will be passed to the function and then be used to address the element later inside the function.

    <script type="text/javascript">
        function random_color(id) {
            // id stores the id of the element that was clicked
            // Get 3 random color values
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);

            // Combine them as a string with string formatting
            var color = `rgb(${r}, ${g}, ${b})`;

            // Change the color of the element according to the passed id
            document.getElementById(id).style.background = color;
        }   
    </script>

External libraries

Writing code is fun, but using existing code sometimes even more. And on top of that it’s more efficient often.

We’ll include LeaderLine into the example above.

Download leader-line.min.js from the github page. One way: Copy the content of leader-line.min.js into your text editor and save it as leader-line.min.js inside a subfolder js of your web project.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>(Java)Scripted Story</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

    <div id="div-1" class="prevent-select" onclick="random_color('div-1');">1</div>

    <div id="div-2" class="prevent-select" onclick="random_color('div-2');">2</div>

    <!-- Import JavaScript libraries -->
    <script type="text/javascript" src="js/leader-line.min.js"></script>

    <!-- Draw LeaderLines -->
    <script type="text/javascript">
        // Add new leader line from `start` to `end` (HTML/SVG element, basically).
        new LeaderLine(
          document.getElementById('div-1'),
          document.getElementById('div-2')
        );

    </script>

    <!-- Change background colors -->
    <script type="text/javascript">
        function random_color(id) {
            // id stores the id of the element that was clicked
            // Get 3 random color values
            var r = Math.floor(Math.random() * 256);
            var g = Math.floor(Math.random() * 256);
            var b = Math.floor(Math.random() * 256);

            // Combine them as a string with string formatting
            var color = `rgb(${r}, ${g}, ${b})`;

            // Change the color of the element according to the passed id
            document.getElementById(id).style.background = color;
        }   
    </script>

</body>
</html>

External JavaScript files are loaded into a document similar to loading external CSS files:

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

As our own JavaScript code increases in size, it’s maybe a good idea to put it into an external file:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>(Java)Scripted Story</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

    <div id="div-1" class="prevent-select" onclick="random_color('div-1');">1</div>

    <div id="div-2" class="prevent-select" onclick="random_color('div-2');">2</div>

    <!-- Import JavaScript files -->
    <script type="text/javascript" src="js/leader-line.min.js"></script>

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

</body>
</html>

js/main.js

// Add new leader line from `div-1` to `div-2` (HTML/SVG element, basically).
new LeaderLine(
  document.getElementById('div-1'),
  document.getElementById('div-2')
);

// Assign a random background color to the element that was clicked
function random_color(id) {
    // id stores the id of the element that was clicked
    // Get 3 random color values
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);

    // Combine them as a string with string formatting
    var color = `rgb(${r}, ${g}, ${b})`;

    // Change the color of the element according to the passed id
    document.getElementById(id).style.background = color;
}   

Adding more divs and arguments to LeaderLine:

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>(Java)Scripted Story</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>

    <div id="div-1" class="prevent-select" onclick="random_color('div-1');">1</div>

    <div id="div-2" class="prevent-select" onclick="random_color('div-2');">2</div>

    <div id="div-3" class="prevent-select" onclick="random_color('div-3');">3</div>

    <div id="div-4" class="prevent-select" onclick="random_color('div-4');">4</div>

    <!-- Import JavaScript files -->
    <script type="text/javascript" src="js/leader-line.min.js"></script>

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

</body>
</html>

js/main.js

// Add leader lines
new LeaderLine(
  document.getElementById('div-1'),
  document.getElementById('div-2'), {
    dash: {animation: true}
  }
);

new LeaderLine(
  document.getElementById('div-2'),
  document.getElementById('div-3'), {
    dash: {animation: true}
  }
);

new LeaderLine(
  document.getElementById('div-3'),
  document.getElementById('div-4'), {
    dash: {animation: true}
  }
);

// Assign a random background color to the element that was clicked
function random_color(id) {
    // id stores the id of the element that was clicked
    // Get 3 random color values
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);

    // Combine them as a string with string formatting
    var color = `rgb(${r}, ${g}, ${b})`;

    // Change the color of the element according to the passed id
    document.getElementById(id).style.background = color;
}   

css/style.css

* {
    box-sizing: border-box;
}

body {
    font-family: sans-serif;
    width: 100vw;
    height: 100vh;
    background-color: lightgoldenrodyellow;
}
div {
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
}

div:hover {
    cursor: pointer;
}

.prevent-select {
  -webkit-user-select: none; /* Safari */
  -ms-user-select: none; /* IE 10 and IE 11 */
  user-select: none; /* Standard syntax */
}

#div-1 {
    height: 10vh;
    width: 5vw;
    background-color: orchid;
    position: fixed;
    top: 5vw;
    left: 5vw;
}

#div-2 {
    height: 5vh;
    width: 10vw;
    background-color: salmon;
    position: fixed;
    right: 10vw;
    top: 20vw;
}

#div-3 {
    height: 20vh;
    width: 18vw;
    background-color: cadetblue;
    position: fixed;
    left: 18vw;
    top: 40vw;
}

#div-4 {
    height: 7vh;
    width: 14vw;
    background-color: coral;
    position: fixed;
    right: 30vw;
    bottom: 40vw;
}

The code to create the leader lines is almost the same so it’s very repetitive. According to one of the principles of programming (DRY(I) - Don’t repeat yourself (Idiot)) we should try to avoid set. It makes the code more modular and maintainable.

js/main.js

// Add leader linses with a for-loop

for (var i = 1; i < 4; i++) {
    new LeaderLine(
      document.getElementById(`div-${i}`),
      document.getElementById(`div-${i+1}`), {
        dash: {animation: true}
      }
    );
}

// Assign a random background color to the element that was clicked
function random_color(id) {
    // id stores the id of the element that was clicked
    // Get 3 random color values
    var r = Math.floor(Math.random() * 256);
    var g = Math.floor(Math.random() * 256);
    var b = Math.floor(Math.random() * 256);

    // Combine them as a string with string formatting
    var color = `rgb(${r}, ${g}, ${b})`;

    // Change the color of the element according to the passed id
    document.getElementById(id).style.background = color;
}   

We can check what a for loop does within our console:

for (var i = 0; i < 10; i++) {
    console.log(i);
}