Skip to content

02. Local interactivity and external JS script

In this lesson, we create a new development branch, add a dropdown menu for selecting buildings, and separate the JavaScript logic into an external script.js file.

flowchart LR User(["🚶 User"]) subgraph System ["Interactive Campus Map (Lesson 2)"] U1(["Select Building from Dropdown Menu"]) U2(["Select Building by Clicking the Map"]) U3(["View Highlighted Building"]) end User --> U1 User --> U2 U1 -.->|"<<include>>"| U3 U2 -.->|"<<include>>"| U3 classDef actor fill:#1e3a8a,stroke:#3b82f6,color:#fff,stroke-width:2px; classDef usecase fill:#2563eb,stroke:#1d4ed8,color:#fff,stroke-width:2px; classDef system fill:#f8fafc,stroke:#64748b,stroke-width:2px,color:#0f172a; class User actor; class U1,U2,U3 usecase; class System system;

Diagram created with Mermaid

At the end of this lesson, the project folder will contain three main files in the root directory:

  • Directorycampus-map/
    • index.html Main HTML page containing the SVG structure and selection menu
    • style.css Stylesheet for page layout, graphics, and building highlights
    • script.js JavaScript file containing the logic for selecting buildings and updating the DOM
sequenceDiagram actor User participant HTML as index.html / DOM participant JS as script.js participant CSS as style.css alt Selection from Dropdown Menu User->>HTML: Select an option in the <select> (onchange) HTML->>JS: Call highlightBuildingFromMenu() else Direct Selection from Map User->>HTML: Click an SVG building (onclick) HTML->>JS: Call selectFromMap(buildingId) JS->>HTML: Update the <select> value end JS->>JS: removePreviousSelection() JS->>HTML: document.getElementById(selectedId) HTML-->>JS: Return the building's SVG element JS->>CSS: Add the .active class CSS-->>User: Highlight the building (yellow border and glow)

Diagram created with Mermaid

graph TD subgraph Client [Client Environment] Browser[Web Browser] end subgraph ProjectFiles [Project Files] HTML[index.html] -->|Links stylesheet| CSS[style.css] HTML -->|Contains and structures| SVG[Map SVG Structure] HTML -->|Runs logic| JS[JS Script / Interactivity] subgraph SVG_Structure [SVG Composition] SVG --> Terrain[Terrain Layer] SVG --> Paths[Paths Layer] SVG --> Buildings[Buildings & Labels Layer] end end Browser -->|Loads and renders| HTML %% Visual styles for the diagram classDef browser fill:#1e3a8a,stroke:#3b82f6,color:#fff,stroke-width:2px; classDef html fill:#2563eb,stroke:#1d4ed8,color:#fff,stroke-width:2px; classDef cssSvg fill:#059669,stroke:#047857,color:#fff,stroke-width:2px; classDef layer fill:#0d9488,stroke:#0f766e,color:#fff,stroke-width:1px; class Browser browser; class HTML html; class CSS,SVG,JS cssSvg; class Terrain,Paths,Buildings layer;

Diagram created with Mermaid

Before we start writing the new code, create a dedicated branch to isolate the changes for this lesson:

  1. Open the Source Control panel in VS Code (Ctrl + Shift + G).
  2. Click the current branch name in the lower-left corner (or at the top of the panel), then select Create New Branch....
  3. Enter the name of the new branch: lesson-2, then press Enter.

Updating style.css (Hover Effects and the active Class)

Section titled “Updating style.css (Hover Effects and the active Class)”

Add the visual rules for the mouse cursor and the highlight effect (yellow border and glow) to the bottom of your style.css file when a building is selected:

style.css
/* style for building text labels */
.label {
font-size: 14px;
font-weight: bold;
fill: #ffffff;
text-anchor: middle;
dominant-baseline: middle;
pointer-events: none;
}
/* part to add at the bottom of the file */
/* Hover effect on all building groups */
#layer-edifici > g {
cursor: pointer;
transition: opacity 0.2s ease;
}
#layer-edifici > g:hover {
opacity: 0.85;
}
/* Style applied to the building SELECTED through JS */
.attivo rect {
stroke: #facc15 !important; /* Bright yellow */
stroke-width: 5px !important;
filter: drop-shadow(0px 0px 10px #facc15);
}

Creating script.js and using document.getElementById()

Section titled “Creating script.js and using document.getElementById()”

Create a new file named script.js in the project’s root folder.

Inside it, add a function that uses document.getElementById() to retrieve the SVG element corresponding to the selected building and apply the .attivo class:

script.js
// Function invoked when the dropdown menu changes
function evidenziaEdificioDaMenu() {
rimuoviSelezionePrecedente();
const selectMenu = document.getElementById("select-edificio");
const idSelezionato = selectMenu.value;
if (idSelezionato) {
// Use getElementById to find the SVG element in the DOM
const elementoEdificio = document.getElementById(idSelezionato);
if (elementoEdificio) {
elementoEdificio.classList.add("attivo");
}
}
}
// Function invoked by clicking an SVG building directly on the map
function selezionaDaMappa (idEdificio) {
const selectMenu = document.getElementById("select-edificio");
selectMenu.value = idEdificio;
evidenziaEdificioDaMenu();
}
// Service function to clear the previous selection
function rimuoviSelezionePrecedente() {
const edificioAttivo = document.querySelector(".attivo");
if (edificioAttivo) {
edificioAttivo.classList.remove("attivo");
}
}

To make the map interactive in the second lesson, modify index.html by adding a control panel with a dropdown menu, connecting click events to the buildings, and including the external script.

  1. Adding the control panel with the dropdown menu (<select>)

    Section titled “Adding the control panel with the dropdown menu (<select>)”

    Add the control panel immediately before the <svg> tag.

    index.html
    <h1>🗺️ University Campus Map</h1>
    <!-- CONTROL PANEL WITH DROPDOWN MENU -->
    <div style="margin-bottom: 15px; background: white; padding: 10px; border-radius: 8px; border: 1px solid #cbd5e1;">
    <label for="select-edificio"><strong>🔍 Highlight Building:</strong></label>
    <select id="select-edificio" onchange="evidenziaEdificioDaMenu()" style="padding: 6px; border-radius: 4px; border: 1px solid #0284c7;">
    <option value="">-- Select a destination --</option>
    <option value="edificio-uffici">Administrative Offices</option>
    <!-- TODO: Add the other custom buildings on your campus here (for example, classrooms and laboratories) -->
    </select>
    </div>
    <svg viewBox="0 0 800 600" width="800" height="600" xmlns="http://www.w3.org/2000/svg">
  2. To allow each building to respond to a mouse click, connect the onclick="selezionaDaMappa(...)" attribute to the <g> groups for the individual buildings inside <g id="layer-edifici">.

    index.html
    <!-- LAYER 3: CAMPUS BUILDINGS -->
    <g id="layer-edifici">
    <g id="edificio-uffici">
    <!-- Add the onclick attribute linked to the JavaScript function -->
    <g id="edificio-uffici" onclick="selezionaDaMappa('edificio-uffici')">
    <rect x="70" y="80" width="100" height="140" fill="#1e3a8a" rx="6" />
    <text x="120" y="150" class="label">Offices</text>
    </g>
    <!-- Repeat for the other buildings... -->
    <!-- TODO: Extend the onclick="selezionaDaMappa('building-id')" attribute to all other buildings in your SVG -->
    </g>
  3. Finally, immediately before the closing body tag (</body>), add the reference to script.js, which contains the control logic.

    index.html
    </g>
    </g>
    </svg>
    <!-- Link to the external JavaScript file -->
    <script src="script.js"></script>
    </body>
    </html>

Final Commit and Synchronization (Git / GitHub)

Section titled “Final Commit and Synchronization (Git / GitHub)”

Now that Lesson 2 is complete and tested in the browser, save the work in the repository:

  1. Return to the Source Control tab in VS Code.
  2. Verify that the modified and newly created files appear: index.html, style.css, and script.js.
  3. Write a clear commit message in the text box, for example: “Completed Lesson 2: Local interactivity, dropdown menu, and script.js”.
  4. Click the Commit button.
  5. Click Publish Branch (or Sync Changes) to upload the new lesson-2 branch and its commits to your remote GitHub repository.

The answers to this page's quizzes are saved in your browser's local storage and remain stored between visits

What is the purpose of the <select> menu in the interactive map?

  • Automatically display all buildings in 3D.
  • Allow the user to choose the building to highlight.

    Correct: the selected value is read by the JavaScript function to identify the corresponding SVG element.

  • Connect the script.js file to the HTML page.

Which HTML attribute detects a change in the dropdown selection?

  • onclick="evidenziaEdificioDaMenu()"
  • onchange="evidenziaEdificioDaMenu()"

    Correct: onchange runs when the value of the <select> menu changes.

  • src="script.js"

Which statement returns the page element corresponding to a specific id?

  • document.querySelectorAll()
  • document.getElementById(idSelezionato)

    Correct: getElementById() retrieves the SVG building selected by the user from the DOM.

  • selectMenu.value = idEdificio

Which method adds the .attivo class to the selected building?

  • elementoEdificio.remove()
  • elementoEdificio.style()
  • elementoEdificio.classList.add("attivo")

    Correct: classList.add() applies the class that activates the selected building’s CSS style.

What does the attribute onclick="selezionaDaMappa('edificio-uffici')" allow you to do?

  • Remove the building from the map when it is clicked.
  • Select the building and update its highlight when it is clicked on the map.

    Correct: the click passes the building identifier to the JavaScript function, which also updates the menu.

  • Create a new option in the <select> menu.

What is the purpose of the rimuoviSelezionePrecedente() function?

  • Remove all SVG buildings from the DOM.
  • Temporarily disable the dropdown menu.
  • Remove the attivo class from the previously selected building.

    Correct: this ensures that only one building is highlighted at a time.

Where is the external JavaScript file script.js linked in the HTML page?

  • At the beginning of the <head> section using a <style> directive.
  • Before the closing </body> tag using <script src="script.js"></script>.

    Correct: the external link loads the JavaScript functions without inserting the code directly into the HTML.

  • Inside the viewBox attribute of the <svg> element.

Quiz progress

0 / 0 questions answered (0%)

0 correct answers