Javascript Basics

In this section we'll first setup a javascript file so that it runs on our homepage. We'll then cover the basic syntax of javascript. After that we'll jump right into jQuery in the next section.

Creating and Linking a Javascript File

Create the file index.js inside of the static/js/ folder that we created a few sections ago:

Next we have to tell our index.html file to load the index.js onto the page. The template for importing a javascript file is as follows:

<script src="/path/to/file"></script>

We generally place javascript imports at the bottom of the body, as you might have noticed we did for the bootstrap javascript files. Another thing is that you should import javascript lower down in the HTML underneath other javascript libraries that your file will depend on. For example, our file is going to rely on jQuery. If we imported the files as follow,

<script src="/path/to/file"></script>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>

then the browser would tell us that jQuery is not defined in our file because it was imported later on. This is the same as how you have to import a module in python before you can use it.

Similarly to the CSS import, we have to use special django syntax to import our javascript file:

<script src="{% static 'js/index.js' %}"></script>

This will tell Django to look into the static folder in our web app.

Printing in Javascript

It is critical to know how to print when coding because that is often the best way to debug code. Printing in javascript is pretty straightforward. Instead of doing print() like in python, the command is:

console.log("wooo")

Place that code into your index.js and save it. Now when you refresh the page "wooo" will be printed out somewhere. But where?

Using the Console

Earlier we talked about the developer tools and the inspector. Those tools are even more important now that we have javascript because the console is where all of our printing and error output is going to go.

Open up the inspector by right-clicking on the page and hitting inspect. Then, go to the console tab and confirm that "wooo" was printed out:

Note: Every time you are writing javascript and the code isn't working the way you expect, be sure to check the console to check on any errors you might be getting which could point you into the right direction.

results matching ""

    No results matching ""