Javascript, Generative

About this guide

If you are following our guides so far, you probably have a good understanding about how HTML and CSS interact with each other and the possibilities within the language. But what if you need more? What if the site needs to respond to the user or time in a specific way? In this guide, we'll take a look at some ways JavaScript can add features to a website.

Note: learning JavaScript takes a long time and might be frustrating at first. The best way to approach it is by starting with what you're trying to do and studying how others have done it. So be patient, open up your web inspector, and have fun!

Note: our weekly guides aim to provide a general landscape ... an overall survey of what’s most essential about the technology at hand and the basics of how to use it. From a technical or skill perspective, our guides are not exhaustive or thorough because there are already many other resources on the internet that are just that. We encourage you to check them out -- we’ve linked some.

Part 0. Change Over Time

a plant showing a fractal

The plant above shows a fractal that happens in nature ... fractals are infinitely complex patterns that are self-similar across different scales. They are created by repeating a simple process over and over in an ongoing feedback loop.

The internet is a network ... similar to this plant, every leaf connects and relates to it's nearest neighbor. It's inherently generative in that way. JavaScript allows us to access that generative potential to use the network as a medium ...

CĂ©leste Boursier-Mougenot featuring 70 zebra finches
Above is an installation by French artist CĂ©leste Boursier-Mougenot featuring 70 zebra finches and a slew of tuned, amplified guitars. As the birds nest, feed, flock, and perch on guitars and cymbals, the sonic experience unfolds.

Let's say this piece illustrates users on a website. The birds represent people, the guitar represents the interface, the output is sound and maybe the gallery is the server ... The point is, CĂ©leste has no ideas what these birds are going to do but he has a good idea of what the output will sounds like.

In that way it's a dynamic system that changes with context, time and birds. JavaScript is designed to make dynamic systems just like this ...

JavaScript has many definitions because it has many different use-cases ... let's take a look at this one from CodeAcademy:

JavaScript is a lightweight programming language that powers the dynamic behavior on most websites. Alongside HTML and CSS, it is a core technology that makes the web run.

There are many applications for JavaScript on the web ... things as simple as a slideshow to complex frameworks. You could even simulate that fractal! for the purpose of this class, we'd like to show how you can use JavaScript in a generative way.

HTML CSS as squares, JS as star

CSS and HTML is a one-way relationship: CSS effects the layout and styling of our HTML markup. When we add JavaScript into the mix, a two-way arrow is needed. JavaScript is an on-going dialogue with your CSS and HTML ... changing with interactions, time, etc.

JS is about be star

If HTML and CSS are square documents, defined by the limits of the document, then JS is a star with points ... each point acting as a receiver to not only the other documents but API'S, databases, libraries, etc. And in a lot of ways, JavaScript allows you to use the network of the web as a medium and define how the website behaves.

1. In Use

a brief history ...

Coding websites with JavaScript is quite common now. You may of heard of things like Angular or React ... These have a pragmatic goal of replacing front-end practices like writing HTML by hand ... we're not interested in that. We're interested in adding features to our web pages to express our seeds ... let's look at some sites using generative potential, like this generative lemon of the fruitful blog:

Part 2. Reference

Setup

This reference is a dense documentation around the terms associated with JavaScript. If you're more of a visual learner, I'd recommend scrolling down to the demos and cross-reference terms as you go.

So ... how do you connect JavaScript to your HTML? You can include JavaScript in your HTML in two ways:

For the most part, you will include the JavaScript as an external file and this script tag should be included between the <head> tags in your HTML document.

console.log()

let's try something together before we jump in:

The console.log() is a JavaScript function that writes to the log on the console in your web inspector. You will not see anything on the screen but in a <script> tag I've written console.log('🍓') to output the strawberry to the log. This will be used quite a bit to test outputs of a function, variables, etc..

Variables

Variables are used to store something (data). A variable contains info that can be used, updated or changed elsewhere in the script.

var name = "john";
let location = "New York";
const birthplace = "Maine";

var & let is the preferred way to declare a variable when it needs to be reassigned over time ... while const is the preferred way to declare a variable with a constant value.

you may have also noticed that I've been ending each line of variables with ; ... this a convention that won't break your code with or without it but it's better to have it in a consistent way. Other programming languages will break if you don't have it, similar to CSS!

Strings

Strings are a primitive data type. They are any grouping of characters (letters, spaces, numbers, or symbols) surrounded by single quotes ' or double quotes ".

var name = "john";

Integers

Integers are also a primitive data type. They include the set of all integers and floating point integers. Basically ... numbers!
var age = 28;

JavaScript also supports arithmetic operators for:

console.log( age * 2 );
result would be 56

you can also update to an existing value using operators like so: 3 += 1;
result could be 4

JavaScript offers math methods to generate whole or random numbers:

console.log( Math.random() * 3 );
result could be 1.2343224 or 2.5127636 or 0.2313123 and so on ...

console.log( Math.floor( 2.5127636 ) );
result could be 3

Booleans

Values can have a value of true or false when evaluated as a boolean.

Booleans only have these 2 values and are separate from strings because they have no " or '. They are often used to write conditional statements, which we'll get to later.

Arrays

Let's say I want a variable to have a list of data rather than just one piece of data. We'd use an array to store multiple pieces of data to act as a list-like object.

var colors = [ "green", "pink", "skyblue", "yellow", "grey"]

It's set up like any other variable. We write out the strings with quotes and separate the list items with commas ,. surrounding the list are square brackets [ ] to indicate that we want to declare this variable as an array.

console.log( colors.length )

The above log would return a number of the total items in a given array ... in this case 5. How do we specify a single color in the array?

console.log( colors[0] )

The above log would return "green". If I were to specify console.log( colors[4] ), it would output "grey".

colors.push( "teal")

What if I want to add an item to the array? Above I pushed "teal"to the array and now the array is updated:
var colors = [ "green", "pink", "skyblue", "yellow", "grey", "teal"]

Objects

Objects are kind of like arrays in the sense that they can store multiple items of data.


        const person = { 
            name: ['John', 'Provencher'], 
            age: 28, 
            location: 'New York' 
            };
            

It's kind of like variables within a variable ... and it can be useful when you need to assign data to a single thing. How do I target the age in this example?

console.log( person.age )

The above log would return 28.

Functions

So now that we covered all / most of the ways to define and store data, how do we actually do something? We define functions!

            
        function functionName( myNumber ) { 
            console.log( myNumber * 2 );
        };
        

The code above won't do anything. Functions are called elsewhere in script using parentheses following the function name. When a function is called, the code defined inside the function will run. When you call a function, you can pass an appropriate piece of data through the argument. In this case, we're multiplying the parameter myNumber so let's pass a integer of 2.

            
        function functionName( myNumber ) { 
            console.log( myNumber * 2 )
        };
        
        functionName(2)
        
        //returns 4 in the console
        

Once a function is defined, it can be called multiple times, anywhere in your script. What about a function over time?

            
        setInterval ( function() { 
            var d = new Date();
            var t = d.toLocaleTimeString();
            console.log(t)
        }, 1000)
                
        //returns the current time in the log every 1000ms ( 1 second )
        

setInterval allows you to run a function ever desired ms. In this case, every 1000ms we create a variable using a new Date(); method (which gives us a timestamp). We render that timestamp object to get the local time with var t = d.toLocaleTimeString(); and then we log it to the console.

Conditions

A conditional statement is trying to see if something is true or not ... It's comprised of the if keyword, a condition, and a pair of curly braces { }. If the answer to the condition is yes, the code inside the curly braces will run.

            
         var age = 21; 
         if( age >= 20) { 
             console.log(“You are older or exactly 20 years old”); 
          };
        

The code inside the curly brackets only runs if condition returns yes. You can also do something if it's no with an else statement.

            
         var lie = false; 
         if( lie === true) { 
                console.log(“Yea that sounds right”); 
          }
          else {
                console.log(“No, that sounds like a lie”);
          };
        

For Loops

A for loop declares looping instructions, with three important pieces of information separated by semicolons:

            
        for (let i = 0; i > 4; i++) { 
        console.log(i); 
        }; 
        
        // Output: 0, 1, 2, 3 
        

These method can be really effective when going through an array list:

 
        var colors = [ "green", "pink", "skyblue", "yellow", "grey"]
        for (let i = 0; i > colors.length; i++) { 
        console.log( colors[i] ); 
        }; 
        
        // Output: "green", "pink", "skyblue", "yellow", "grey"
        

inside the for loop function, i becomes the number of the itteration so it becomes a value that is contstantly increasing.

DOM

there are quite a few frameworks to select and manipulate front-end HTML and CSS (like jQuery which we talk about later). But there's ways to do this with what is known as vanilla JS, or just JS without libraries or frameworks.

You can select an element using a

var orangeElement = document.querySelector(“#orange”);

You can change the contents within the tag using innerHTML

orangeElement.innerHTML = "orange"

You can change the CSS property and value using .style.cssValue

orangeElement.style.backgroundColor = "orange"

Libraries

There are many, many, many libraries / frameworks out there that turn JS into a tool for a broad or specific function:

One most commonly used framework is jQuery ... here's the definition from their website:

"jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript."

Ultimately, jQuery makes it easier to work directly with HTML and CSS through JS. How do I link a library? First, let's download a version of jQuery and call it jquery.js in our directory. Then, let's link it just like any other script:

            
<script type="text/javascript" src="jquery.js"> </script>
<script type="text/javascript" src="path-to-javascript-file.js"> </script>
        

It's important to note that jQuery is referenced first ... This is important and order matters!

Now what? All frameworks will likely have a documentation of functions to use. Let's look for an example here: jQuery documentation ... okay, let's take a look at the .css() function.

            
   $('#div-id').css('color', 'black')
        

This is the basic syntax for most of jQuery. Starting with a $, defining a selector with ('class, id, tag selector in here') followed by a period and other actions ... in this case .css('property', 'value')

            
   $( 'body' ).mousemove(function( event ) {
    $( this ).text( event.pageX + ", " + event.pageY );
   });
        

jQuery also makes it very easy to trigger changes on interaction. In this code example above, every time my mouse moves it will trigger an event ... I can then read the event.pageX event.pageY to get the location of the mouse. I then print those results as text using $( this ) which refers the the body previously defined.

Frameworks have languages of their own that build off of JS but are specific to themselves. This is a small sample of what you can do with jQuery so if you're interested in learning more, check out the documentation and try some examples out!

Advanced: API's and Databases

This might be a section to come but it's worth talking about. You may want a website that reacts to the weather ... or you want users to be able to chat on your website. This involves reading and potentially writing to other documents on the web using JS. If you feel like you have a good handle on JS, consider exploring the following:

API's

API stands for application programming interface. An API is a way to programmatically interact with separate resources.

weather API

If you're interested in learning about API's, I'd start simply with reading the OpenWeather API documentation for weather. There are a ton of other API's, even a Pokemon API.

Databases's

A database is a structured set of data held in another computer and that is accessible in variety ways. It's kind of like an excel sheet that you can edit with a website.

Mongo DB

If you're interested in learning about database's, I'd start by checking out something like MongoDB ...

an open source NoSQL database management program. NoSQL is used as an alternative to traditional relational databases. NoSQL databases are quite useful for working with large sets of distributed data. MongoDB is a tool that can manage document-oriented information, store or retrieve information.

There are a lot of great things you can do with these sorts of technologies but they get a little more advanced with things like security and access keys ...

Part 4. Demos

Let's apply some of what we've been referencing above to real examples.

( 1 ) Dark Mode

open in glitch

The goal is to create a web-page with not only dark-mode capabilities, but also turning back to light mode and even being able to type a custom color. Let's make this using only vanilla JS and HTML inputs.

in our HTML, we set up buttons with the attribute to fire functions onclick

button onclick="lightsOn()"
button onclick="lightsOff()"

in our JS, let's variable the elements we want to change using a querySelector

var body = document.querySelector('body');
var message = document.querySelector('#message');

we can now write some functions that turn the lights on and off

    
        //triggered on the button for light color
        function lightsOn() {
           body.style.backgroundColor = "white";
           body.style.color = "black";
           message.innerHTML = "the light is on ..."
           }

        //triggered on the button for dark color
        function lightsOff() {
           body.style.backgroundColor = "black";
           body.style.color = "white";
           message.innerHTML = "the light is off ..."
           }
            

now let's write a function that looks for a CSS acceptable color format when typed into this input ... this function will be called everytime I type in the input box using an addEventListener. We then pass back the argument e.target.value to get the color written in the box.

    
        //triggered on the input for custom color
        var input = document.querySelector('input');
        input.addEventListener('input', customColor);

        function customColor(e) {
            body.style.backgroundColor = e.target.value
            body.style.color = "white";
            message.innerHTML = "the light is " + e.target.value + "..."
        }
            
see code

( 2 ) Schedule

open in glitch

The goal of this page is to create 2 different styles / content for when the site is open and closed. To do this, we need to get the time, evaluate it and apply a style accordingly. Let's start with the CSS:


.open {
  background: rgb(246,255,112);
  background: linear-gradient(180deg, rgba(246,255,112,1) 0%, rgba(255,255,255,1) 50%, rgba(219,219,219,1) 100%);
  color: black;

}

.closed {
  background: rgb(0,39,182);
  background: linear-gradient(180deg, rgba(0,39,182,1) 0%, rgba(0,0,0,1) 50%, rgba(89,89,89,1) 100%);
  color: white;
}
        

I have 2 classes that I want to apply to the body depending on what time it is. I want to apply .open from 7AM to 7PM, otherwise it's .closed ...

            
            var date = new Date();
            var time = date.toLocaleTimeString();
            var today = date.getHours();
            
            //apply the time to the html element
            $("#time").text(time);

            

Now that we know the time, we can evaluate if it's open or closed using a condition:

            
            //check if opened, else closed
            if (today >= 7 && today <= 19) {
                //remove and add class to change the gradient of the bg
                $("body").removeClass("closed");
                $("body").addClass("open");

                //toggle between messages
                $("#open-message").css("display", "block");
                $("#closed-message").css("display", "none");
            } else {

                //remove and add class to change the gradient of the bg
                $("body").removeClass("open");
                $("body").addClass("closed");

                //toggle between messages
                $("#open-message").css("display", "none");
                $("#closed-message").css("display", "block");
            }
            

let's wrap the whole thing into a function called schedule() so that we can call it every minute in the setInterval( function(){},60000)

            
        function schedule() {
            var date = new Date();
            var time = date.toLocaleTimeString();
            var today = date.getHours();
            
            //apply the time to the html element
            $("#time").text(time);

            //check if opened, else closed
            if (today >= 7 && today <= 19) {
                //remove and add class to change the gradient of the bg
                $("body").removeClass("closed");
                $("body").addClass("open");

                //toggle between messages
                $("#open-message").css("display", "block");
                $("#closed-message").css("display", "none");
            } else {

                //remove and add class to change the gradient of the bg
                $("body").removeClass("open");
                $("body").addClass("closed");

                //toggle between messages
                $("#open-message").css("display", "none");
                $("#closed-message").css("display", "block");
            }

        }
        //initialize function
        schedule();


        setInterval(function() {
        //check time every minute
            schedule()
        }, 60000);

            
see code

( 3 ) Screensaver

open in glitch

the goal with this web page is to create a screensaver where an orb of light randomly changes color and position throughout the screen.

We've created a #circle div on our HTML ... Now let's take a look at the CSS. I'm going to set the position to absolute so I can freely move the circle around the screen, set the size and radius of the circle and set a transition: 2.5s ease to trigger animation when I change the attributes in JS

  
    #circle {
        position: absolute;
        border-radius: 150px;
        width: 300px;
        height: 300px;
        top: 0;
        left: 0;
        transition: 2.5s ease;
        filter: blur(80px)
    }
        

Let's start writing our script. The variables we'll need is the height and width of the document ( minus the size of the circle ) and an array of colors to choose from randomly:

            
            var width = $(document).width() - 300;
            var height = $(document).height() - 300;
            var colors = ["cyan", "pink", "green", "#00ff00", "red", "yellow", "skyblue", "tan"];
            

Let's define variables and apply them to CSS using jQuery. We'll be using the width we just defined to generate a Math.random() number. And let's add "px" to the end so that the CSS can read it:

            
            function update() {
               //random position
                var positionLeft = Math.random() * width + "px";
                var positionTop = Math.random() * height + "px";

                $("#circle").css("left", positionLeft);
                $("#circle").css("top", positionTop);

            }
            update();
            

Let's add 3 lines to apply a random color. We need a whole number Math.floor() that includes Math.random() * the length of our color array to create our randomNumber variable. We use that number to select an item in the array and then apply it to our CSS.

            
            function update() {
               //random position
                var positionLeft = Math.random() * width + "px";
                var positionTop = Math.random() * height + "px";

                $("#circle").css("left", positionLeft);
                $("#circle").css("top", positionTop);
                
                //random color
                var randomNumber = Math.floor( Math.random() * colors.length );
                var randomColor = colors[randomNumber];
                $("#circle").css("background-color", randomColor);
            }
            update();
            

Let's run this code every five seconds:

            
            //random color and position every 2 second
            setInterval(function() {
                update();
            }, 5000);
            
see code

Feel free to use these examples to explore different opportunities. The great thing about JS is that it's very flexible ... you can take however much of the code you need and add to it. Have fun!

đź”— Further JS resources

🍋 Try this

Demo: Shuffle

download source code

for this week, we're going to interact with JS without having to write much. I've made a basic image and text shuffler that I'd like you to change the content and style of and maybe experiment with adding more JS.

requirements:

When you're done, upload this file to your personal demos/ folder in the portal.