/javascript-training

OWH brown-bag sessions 2015: Javascript!

Primary LanguageHTML

#Javascript Javascript is the scripting language that powers the web. You can use it to animate page elements, handle information submitted by the people who visit your web page and generally create more sophisticated interactive content than you could with HTML and CSS alone.

Most of our maps and charts and other assorted widgetry depend on Javascript.

###Session outline

  1. Real-world examples
  2. Alerts, prompts and logging
  3. Targeting elements
  4. Changing HTML content or styles
  5. Variables
  6. Functions
  7. Event Listeners
  8. Validating inputs
  9. Working with data: If-else logic
  10. Working with data: Objects and arrays
  11. Working with data: The for loop
  12. Working with data: Looping over data to construct HTML
  13. Using developer tools to debug your code

###console.log("roll up those sleeves") If you're writing Javascript directly in an HTML file, as we'll do today, you need to wrap it in a <script> tag. That tells the browser: Hey! You're about to see some Javascript. Interpret accordingly.

Later, as your scripts get more complicated, you'll want to save your scripts in a separate file and link to it from your HTML file, similar to how you linked to an external CSS file in the last session. It's not required, but it's best practice-y to separate page structure (HTML) from design rules (CSS) from interactivity (Javascript).

###Working with data

#####String "Hello there, I am a string."
"234"
"true"

#####Number 213
3.043

#####Date new Date()

#####Boolean true
false

###Comments To insert a comment — a note explaining some code — prepend two slashes:

<script>
    function (x) {
    // This message won't be interpreted by your browser
    return x - 30;
    }
<script>

Enclose multiline comments in /*    */:

<script>
    /*
    I am a multi-line
    comment
    look at me
    being all
    multi-liney
    */
</script>

###Using Javascript to generate HTML Let's say you've got some data that you want to plop on a web page in a repeating pattern. Good news! You can use Javascript to simplify the process.

Here's what a basic HTML table looks like behind the scenes:

<table>
    <tr>
        <td>
        Apples
        </td>
        <td>
        10
        </td>
    </tr>
    <tr>
        <td>
        Oranges
        </td>
        <td>
        7
        </td>
    </tr>
    <tr>
        <td>
        Watermelon
        </td>
        <td>
        3
        </td>
    </tr>
</table>

... which renders this:

Apples 10
Oranges 7
Watermelon 3

Not a heavy lift. But it would get old pretty quick if you had 100 things to tabulate instead of three. One solution: Use Javascript to loop over your data and generate the HTML code dynamically. Comme ça:

<table id="fruit_table"></table>

<script>
// store the data as an array of objects
    var fruit = [
        { 'name': 'Apples',
          'count': 10
        },
        { 'name': 'Oranges',
          'count': 7
        },
        { 'name': 'Watermelon',
          'count': 13
        }
   ]

// make a variable called table_content   
   var table_content = '';

// start a loop
   for (i=0;i<fruit.length;i++) {

// for each loop, add data to the table_content variable
        table_content += [
        '<tr><td>',
        fruit[i].name,
        '</td><td>',
        fruit[i].count,
        '</td></tr>'
        ].join('')
   }

// finally, set the table HTML equal to table_content
   document.getElementById('fruit_table').innerHTML = table_content;
</script>

You'll find another example of this in the file called journos.html in the examples folder. Add new entries to the file called journos.js, which is in the folder examples/data, then reload the page and see what happens.

You'll find a more advanced example of HTML concatenation in the file animals.html in the examples folder, which uses data from one of my favorite Wikipedia pages ever, List of English terms of venery. I pulled my favorite entries into a spreadsheet and then used Mr. Data Converter to convert the rows and columns of my spreadsheet into a data structure that Javascript understands. I saved the data in a file called animals.js, which you will find in examples/data, and which is linked to in the HTML file.

The basic idea was to make a page with a dropdown menu using the HTML <select> tag. When a user selects an option from this menu, the page will display the type of animal and its collective noun (e.g., "a shrewdness of apes").

###Tips

  1. Pay attention to the order in which you import Javascript libraries. If you have a script that needs jQuery to work, make sure you import jQuery first.
  2. Use Chrome or Firefox. Seriously. Both have handy developer tools that will make debugging Javascript much easier.
  3. Use console.log() statements liberally when debugging your scripts. Check the console for errors or use it to test out code. To view the console, try F12 or, if you're on a Mac, Command + Option + I.
  4. Use lots of comments to explain what you're doing. Your future self will thank you.
  5. Pay attention to capitalization
  6. Javascript can be finicky about semicolons; here's a handy guide

###Resources