Here are some examples with a bit of annotation that I hope are helpful to you in your JavaScript adventures!
— David
Creating Content with DOM and innerHTML Examples
Here, we get started by iterating through data structures, and using either DOM methods to create content or using "string" values for our content and using innerHTML to add those to the page.
- fruits0.html — iterate through a simple array (list) of fruits and create an unordered list using DOM nodes.
- fruits0b.html — iterate through a simple array (list) of fruits and create a string value for our HTML content and then use innerHTML to place in the container on our page.
- fruits0c.html — here our data structure is more complex, and we are using DOM nodes to create our content. I hope the main purpose of this is to convince you that "templates" are worth learning and will make creating content from data easier!
Template Examples
{
"apples" : [
"Granny Smith",
"Macoun",
"Empire",
"Honey Crisp",
"Albemarle Pippin"
],
"oranges" : [
"Naval Orange",
"Tangelo",
"Clementine",
"Valencia Orange"
]
}
- fruits1.html – Iterate through data and use DOM methods to build up content from data structure.
Key aspects are:
for (let f in fruits) { }to iterate through keys (f) and access values (fruits[f])for (let type of fruits[f]) { }to iterate through array- DOM methods of
createElement,createTextNode,appendChild,replaceChildren, and our old favoritegetElementById. - Using CSS to capitalize apples and oranges with
text-transform: capitalize
- fruits2.html – Use a Handlebars template print out a list of apple types.
Key aspects are:
- Create the template
<template id="fruit-template"> <ul> {{#apples}} <li>{{.}}</li> {{/apples}} </ul> </template> - In HTML, load Handlebars library from jsdelivr CDN via
scriptelement. Remember that loading Handlebars must come before Javascript that uses Handlebars! - In JS, get the text of the template via
innerHTML, and then compile withHandlebars.compile(), and then execute the resulting compiled templatewindow.addEventListener("DOMContentLoaded",function(){ let fruitTemplateResults = ""; let fruitTemplate = document.getElementById('fruit-template').innerHTML; let fruitCompiledTemplate = Handlebars.compile(fruitTemplate); fruitTemplateResults = fruitCompiledTemplate(fruits); console.log(fruitTemplateResults); document.getElementById('fruitlist').innerHTML = fruitTemplateResults; });
- Create the template
- fruits3.html – Use a Handlebars template iterate through all the fruits and their types.
Key aspects are:
- Create the template. When
each-ing throughfruits,@keyin Handlebars refers to the key andthisis how to access the value of that key. Not the most intuitive, but we'll make improvements in fruits4.html<template id="fruit-template"> {{#each fruits }} <h2>{{@key}}</h2> <ul> {{#this}} <li>{{.}}</li> {{/this}} </ul> {{/each}} </template>
- Create the template. When
- fruits4.html – Let's restructure our data a bit to make it easier to use. We have the same data, but we'll use a list of fruits, and have a name and a variety for each of the fruits. Key aspects are:
- New data structure is:
{ fruits: [ { type: "Apples", varieties: [ "Granny Smith", "Macoun", "Empire", "Honey Crisp", "Albemarle Pippin", ] }, { type: "Oranges", varieties: [ "Naval Orange", "Tangelo", "Clementine", "Valencia Orange" ] } ] } - And this makes our template a bit more intuitive:
<template id="fruit-template"> {{#fruits}} <h2>{{ type }}</h2> <ul> {{#varieties}} <li>{{.}}</li> {{/varieties}} </ul> {{/fruits}} </template>
- New data structure is:
Maps Examples
I'll focus on the use of LeafletJS and OpenStreetMap (OSM) tiles.
- map-1.html. Map using LeafletJS and OpenStreetMap (OSM) tiles. Center on the John Harvard Statue and also put a marker on that spot.
Some notes:
- Load LeafletJS via CDN —- making sure that I include the CSS first and then the JS for Leaflet, as per Leaflet documentation.
- John Harvard Statue data is:
let johnHarvardStatue = { name : "John Harvard Statue", description: "The John Harvard statue is nicknamed the 'statue of three lies.'", lat : 42.374474, lng : -71.117207 } - Once the LeafletJS library is loaded, I now have the Leaflet object (
L) that I can use.
As in,
let map = L.map("map-container");
where "map-container" is theidof the markup element where I want my map placed. - And note that I need to specify a heigth for my map container. In the CSS, I used viewport height (vh) units, as in
#map-container { height: 80vh; }
1vh is 1% of the initial viewport height. Note there is also a unit vw, which is viewport width. - We also need to set the
L.tileLayerand attribution that we know about by reading the Leaflet documentation and viewing their basic examples.
- map-2.html. Map using LeafletJS and Map Box tiles. Same as in
map-1.html, but uses Map Box tiles instead of OSM. Check out theL.tileLayerto see the differences between Map Box and OSM inmap-1.html - map-5.html. Map using LeafletJS and OSM and multiple markers from JavaScript data of Ivy League school locations.
- So, here I iterate through a list of schools, creating a marker on the map for each one.
for (let place of schoolsData.schools) { /* do marker stuff */ } - I also use a Handlebars template to create the "popup HTML" for the marker. While the popup HTML is not complex and we could just use string concatenation as we have before, I wanted to show this use of templates, because at some point the HTML will be too complex to string together in JS. Note that I compile the template once, and then execute it for each marker.
- Also, I take advantage of the Leaflet fitBounds method
L.fitBounds()method to set the latitude and longitude "min max" corners of the map. This automatically sets the zoom level, and it ensures that all my markers will be visible. Note that to accomplish this I need to keep an array of all the latitudes and longitudes so I can figure out the min and max. - An aside: I also use a
L.LayerGroupfor all my markers, and note that I need to add the LayerGroup to the map (markersLayer.addTo(map)). While this isn't strictly needed here, I am thinking ahead to having a pull-down of different school conferences that would then populate the map with those markers. It is easier to remove a single layer and create a new one than to remove all the markers existing on the map.
- So, here I iterate through a list of schools, creating a marker on the map for each one.
- Two examples using Google Maps
- map-3.html. Map using Google Maps.
- Maps JavaScript API (registration and API key needed; please don't use mine from the examples beyond light experimentation!)
- Creating Google Map URLs (no API key needed)
- map-4.html. Map using Google Maps and GeoRSS data.
Learn more about Google Maps and GeoRSS and view the Ivy League GeoRSS file.
- map-3.html. Map using Google Maps.