Simple Web App with Javascript & JQuery

In this tutorial, we’re going to create a simple web app which organizes a list of users profiles into various teams, like you would see in a recreational sports league. This is a good place to start if you are a beginner and understand a little bit of basic Javascript, HTML and CSS. This series will begin to bridge the gap between the minutiae of elementary concepts such as variables/loops and a more realistic web application that you would be expected to work on in real-life.

To view video version, click below:

We are going to use standard tools & libraries on the front end such as Bootstrap, jQuery, Gulp, and of course, HTML/CSS. To save time from writing a full scale backend (with corresponding database, web framework, API, etc), we are going to use Turbo. Turbo is a great and easy way to store data and access it using conventional REST API protocols — the way the professionals do. This makes our practice app more realistic and better training for beginners.

Go ahead to turbo360.co and sign up if you don’t have an account (it’s free).

Installation

To begin, we need to install a few tools. Let’s begin with Gulp; to install, open a Terminal window and enter

$ sudo npm i -g gulp

followed by your password. Then we’re going to need the Turbo CLI:

$ sudo npm i -g turbo-cli

This will scaffold our project and manage deployments, among other things. Now navigate to your workspace in Terminal, and enter:

$ turbo new rec-league --static

This command scaffolds the project. This will be a static app, meaning we’ll just use basic HTML, CSS, JQuery, and Bootstrap. Navgate into the project directory and install the dependencies to download the npm libraries listed in our package.json:

$ cd rec-league
$ npm install

That usually takes a minute or two so while that’s working, go to your Turbo dashboard (turbo360.co/dashboard) and create a corresponding project for our app by clicking CREATE APP. Give it the same name (“rec-league”), hit Create App, and copy the App ID at the top right of the page. Once our $ npm install is finished, we can connect our local project to the server by running (using your app ID of course):

$ turbo app <APP_ID>

To confirm that this worked properly, let’s turn on our local server with the following command:

$ turbo devserver

If you navigate to http://localhost:3000 in your browser, you should see an <h1> tag saying “Welcome to Turbo.”

Turn off our server (in Terminal, hit Ctrl+C), and open the project folder in your text editor (in this exercise, we’ll be using Sublime) to get started.

Getting Started

Let’s take a tour of our project directory. index.html is the page you saw just a moment ago at http://localhost:3000. In it are references to Turbo’s default imports; jQuery, the Turbo SDK, and our custom app code in dist/app/app.min.js.

Our app’s build process is detailed in gulpfile.js. Each gulp.task() transpiles a different piece of the app into a single file of that type (.css, .js) to be easily referenced by index.html. Open a new Terminal tab ($ CMD-t) and run

$ gulp

If you leave this process running, this will enable gulp to watch our files for changes, upon which gulp will run another build process and update our minified files. Let’s begin in assets/js/app.js. To confirm that everything is working properly, in the app.js file, type

..assets/js/app.js

then save. Restart the devserver in a Terminal tab

$ turbo devserver

and refresh http://localhost:3000 in your browser. If you open your browser’s console (command/ctrl+shift+i), you should see the “HELLO REC LEAGUE!” message on pageload.

Now let’s set up the basics of our index.html. Delete the <h1> tag and replace the contents with the following:

index.html

index.html

Here, we set up a simple two-column Bootstrap row which will be used to for adding profiles and eventually teams. We will add users on the left side and teams on the right. Also, the current list of users will appear on the left side in the <div id=”current-users-list”> section (line 20). This is a very standard Bootstrap grid structure and the more web development you do, the more you will see layouts like this.

Adding users

The id attributes in the input fields allow us to reference these form elements in the jQuery we’ll write now. To start, let’s add a click handler to the <button> we just made. In app.js, inside the (function(){})() (all future code we write will be inside this function), add:

..assets/js/app.js

As you can see, the “#btn-add-user” id is used to reference the <button> from the index.html. When the user clicks that button, the callback function inside the .click() function will execute. In this instance, we’re doing two things: preventDefault() so that the form doesn’t submit (thus refreshing the page and trying to submit the form), and logging “ADD USER: “ to our console. Refresh http://localhost:3000 and confirm that when you click the button, that message shows up in your console.

Once you’ve done that, take it a step further by utilizing the form data in your console.log(). Inside the $(‘btn-add-user’).click() handler, create a user object with name and email properties like demonstrated below. Then use the following syntax to assign our form’s values to those properties like so:

..assets/js/app.js

Notice the “console.log(‘ADD USER: ‘ + JSON.stringify(user))” command on line 14. This stringifies (rendering data as a string) our user object to confirm that we’re getting the right information. Refresh http://localhost:3000, enter “bob” for the name and “bob@gmail.com” for the email, and click “Add User.” Your console should now have a new entry sporting our new user’s information:

Once we’ve confirmed we’re getting the information correctly, let’s use this data productively by sending it to our Turbo backend. First, initialize a Turbo object that can connect to Turbo right below the the console log in the app.js like so:

var turbo = Turbo({ site_id: ‘<YOUR_APP_ID>’ })

Beneath that, we’ll use one of Turbo’s functions to send this user object to our backend (If you’re new to Turbo, keep in mind that you can learn about its API functions, such as .createUser(), in the DOCUMENTATION.md file in your project’s root directory). To send the user data up to your Turbo backend, copy lines 16–24 below:

..assets/js/app.js

On line 18, we check the response for an error; if there is one, it will alert the client’s console and use return to end the function. Otherwise, we Console.log() the server’s response if no errors have been flagged in line 23.

So if you refresh http://localhost:3000 and submit “lebron james” and “ljames@gmail.com” with our <form>, in your console you should see a new message saying “USER CREATED: “, followed by a lengthy JSON object containing those two parameters, along with some other information.

On your Turbo app admin dashboard, in your app, if you click “Entities,” you should see the new entry in your User schema. On the right side of the entry, you can click “EDIT” to update this user’s information as you see fit.

Listing users

Since we’ll be using the Turbo SDK throughout our app, let’s initialize the Turbo sdk outside the click handler so we can re-use it several times (line 5 below):

..assets/js/app.js

This allows us to use this one turbo object throughout the app, so we don’t need to re-initialize it again going forward.

To list our existent users and check that we are connecting to our Turbo backend properly on pageload, we can execute a turbo.fetch() function after initializing var turbo like so (lines 7–13):

..assets/js/app.js

Similar to the turbo.createUser() function from before, this function will check to see if any errors were flagged in the server response, then log that response, an object containing the list of all users in our database to the client’s console. If you look more closely at the response, you can see the object contains two keys: “confirmation” (which should read “success” if connection was successful) and “results,” which contains the array of users.

The null is there because the second parameter of turbo.fetch() is used for any filtering of the data you might want the server to perform. Since we want all of the users, we give that parameter null to indicate no filtering should occur.

Now that we have retrieved the list of users, we can display them on our page with a .forEach() function. Add the following code to the bottom of your turbo.fetch() function (lines 13–19):

..assets/js/app.js

This initializes our list (an empty string at the beginning), and for each element of our data.results array (our users), adds an <li> tag containing the user’s name to our list. The list is then sent to our <div> tag in index.html with the id “current-users-list” and rendered on pageload.

You can test this process again by adding another user with the <form> and refreshing to see if that user shows up in the list with Lebron James. Note that Users is a standard resource in any Turbo project, so you won’t need to add it manually.

Adding teams

Next, what we want our app to be able to handle is the Teams our users will be members of. First, in index.html, add a <form> very similar to the one in our Users column (lines 24–28):

index.html

Then, in app.js, set up a click handler which again is initially similar to that of our Users click handler (lines 22–29):

..assets/js/app.js

Like before, your console should log the information you input to the team <form> once you click “Add Team.”

Now, when we were working with our Users, we didn’t need to create a User schema, because Users is a standard resource any Turbo app initializes with. However, Teams is not, so let’s create that now.

To create a schema, we use the turbo.create() function. Add the following to the bottom of your team <form>’s click handler (lines 30–37):

..assets/js/app.js

Filling out the form and submitting it should yield a message in your console indicating the team has been created on your Turbo backend. Refresh your Turbo app admin dashboard tab to see that a new option is available in your Entries page dropdown menu called “TEAM.”

Getting teams data

Now that we can add users and teams, let’s determine what happens next after adding a team. We will redirect to a “/team” page which will show the details and players belonging to the team just created. To do this, first create a new page for team from the root directory of the project:

$ turbo page team

This creates a “team” directory in your project’s root folder, as well as a basic index.html inside it. Next, in the app.js, add to your team <form>’s click handler the following line (line 37):

This will instantly redirect the user to the ‘/team’ page when the click handler reaches this line. Notice the team’s name is prefixed by a hash (#). This will cause the browser to scroll to the tag with the id of that team’s name once the page is loaded. Soon, we’ll start work on our teams page (teams/index.html) to handle this functionality.

In the interest of keeping our project organized, let’s create a separate .js file for our team page. In your Terminal, cd into your assets/js folder and create a new file called team.js:

$ cd assets/js
$ touch team.js

This is where we will write code responsible for the logic on our Team page.

Note that for our app to use teams.js, we’ll need to add it to our Gulp file. In gulpfile.js, create a new gulp.task() by copying the entirety of gulp.task(‘app’), and replacing the parameters appropriately (lines 62–73):

gulpfile.js

This adds the team.js to the overall build process and will compile all of its code in the resulting dist/js/team.min.js file. We separated this out so we can import it only where needed.

Restart the gulp script in your Terminal:

$ gulp

and you should see two new files in your dist/app/ folder — team.min.js and team.min.js.map. We want our team page’s index.html file to use team.min.js instead of app.min.js, so in team/index.html, edit the <script> at the bottom to use that file instead. Then, test this by editing team.js to be like so:

..assets/js/team.js

Make sure your local server is running ($ turbo devserver in the project’s root directory), and navigate to localhost:3000/team#[your team name]. Your console should sport this new message on pageload.

We can actually use the information in the url as part of our console.log() to make it more informative. Edit team.js to look like this (lines 6–14):

..assets/js/team.js

This splits the url into an array containing the substrings before (ideally “localhost:3000/team/#”) and after the hash (your team name). We’re anticipating the url containing exactly one hash, so we set up the if (parts.length == 1) statement to cause the process to crash if there are either 0 or more than 1 hashes in the url. If you refresh localhost:3000/team#[your team name], you should now see just “Hello Team Page: [your team name]” in your console.

Similarly to in our homepage, we’re going to want to fetch our team’s data from the server to display it here. Add the following to the team.js file (lines 15–26):

..assets/js/team.js

Notice that unlike before, we are passing an object to the filter parameter in turbo.fetch() on line 15. This will cause the server to respond only with entries where the team’s name is equal to the teamName designated in our url. If you navigate to localhost:3000/team#[your team name] once again, you’ll see the object attached only to that team in your console.

Additionally, if you navigate to localhost:3000/team#[some nonexistent team name], your console will lack any “Hello Team Page: “ message, and you should receive an alert, as the .fetch() returns out, ending the function, if the team isn’t found (data.results.length == 0).

Utilizing teams data

In the next exercise, we’ll expand on this Teams page by listing the Users we’ll associated with the given team here. Let’s do a little more work on our teams/index.html page now to prepare.

In teams/index.html, add the Bootstrap class “container” to the <body> tag, and id “team-name” to the <h1> tag. Then clear the <h1> of any text (it might currently contain “Team Name”).

In your teams.js .fetch() function, let’s declare var team = data.results[0] (the team should be the only element of the results array) and edit the bottom of the turbo.fetch() to be the following (lines 28–30):

..assets/js/team.js

This will populate the <h1> tag we just added the id “team-name” to with the team’s name. Refresh your localhost to confirm.

Deploying

To close out part 1 of this exercise, let’s deploy our build to a live staging server. End your build and devserver tasks in your Terminal, and run $ npm run build to make sure we’ll be deploying the latest version of our codebase (from root directory of project):

$ npm run build

To deploy, simply run ‘turbo deploy’ from the root directory.

$ turbo deploy

If the deployment is successful, you’ll see a message in your Terminal saying “DEPLOY COMPLETE: “ followed by a url. Copy that url and navigate to it in your browser. This site should be identical to your localhost version of the site.

In part 2, we’ll be going over how we can add functionality to our Teams pages to add Users to those teams directly. Thanks for following along and stay tuned for part 2.