#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
- Real-world examples
- Alerts, prompts and logging
- Targeting elements
- Changing HTML content or styles
- Variables
- Functions
- Event Listeners
- Validating inputs
- Working with data: If-else logic
- Working with data: Objects and arrays
- Working with data: The for loop
- Working with data: Looping over data to construct HTML
- 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
- 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.
- Use Chrome or Firefox. Seriously. Both have handy developer tools that will make debugging Javascript much easier.
- 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.
- Use lots of comments to explain what you're doing. Your future self will thank you.
- Pay attention to capitalization
- Javascript can be finicky about semicolons; here's a handy guide
###Resources