Part 1: Functions and the DOM¶
The HTM-Elements: Avatag the last Airbender¶
Remember, when you see tags in HTML, like <body></body>
, they are referred to as elements, so for example:
<water>Katara</water>
<air>Aang</air>
<earth>Toph</earth>
<fire>Zuko</fire>
Above we have four elements. Each element has a content
, for example, the earth
element’s content is Toph
. Unfortunately, despite how exciting those elements are, the most common HTML element is the <div></div>
element, which is a generic container.
The DOM
(Document Object Model) is basically where HTML elements exists and it has an API (Application Programming Interface) that JavaScript can interact by using functions.
Making JavaScript interact with HTML-ements!¶
Objective
Make a button that we can click on to fly to a location for each of the markers you made.
-
Add a new function to our
addMarker
function -
Create the function to add buttons
-
Add a function to move the map
Creating elements?!
To create HTML elements with JavaScript you need to use the createElement method.
Create the function to add buttons¶
Next we will add our new function. Notice how we are using the lat
,lng
,and title
from the addMarker
function? That’s why it was helpful to do step one first.
function createButtons(lat,lng,title){
const newButton = document.createElement("button"); // (1)!
newButton.id = "button"+title; // (2)!
newButton.innerHTML = title; // (3)!
newButton.setAttribute("lat",lat); // (4)!
newButton.setAttribute("lng",lng); // (5)!
newButton.addEventListener('click', function(){
map.flyTo([lat,lng]); // (6)!
})
document.getElementById("contents").appendChild(newButton); //(7)!
}
- Creates a new button
element
- Gives the button a unique
id
- Gives the button a
title
- Sets the
latitude
- Sets the
longitude
- Tells Leaflet where to
flyTo()
, which is the latitude/longitude - This targets the
id
where the buttons should be added to! In this case it is the div
with the idcontents
!
Call the createButtons()
in our addMarker
function¶
Remember, the only way functions work is if they are called, so the last step is to call the createButtons()
in our addMarker()
function.
function addMarker(lat,lng,title,message){
console.log(message)
L.marker([lat,lng]).addTo(map).bindPopup(`<h2>${title}</h2> <h3>${message}</h3>`)
createButtons(lat,lng,title); //(1)!
return message
}
- This is the line that calls our
createButtons()
function!
Try clicking the button on the webpage and it should fly to the location of that marker!
๐End of Lab Part 1๐¶
This is the end of part 1 for today’s lab!
Let’s change our html
and js
file names, to part1.js
and part1.html
to get ready for the second part of the lab.
Your final code should look like the following:
js/part1.js | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
part1.html | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|