Adding Simulated Functionality with JavaScript

Introduction and Lesson Overview

Welcome back! In our previous lessons, we laid the groundwork for our travel planner application by creating a RESTful API with Flask and rendering a basic HTML page. Now, we are ready to enhance the user experience by adding client-side JavaScript. This lesson will focus on implementing JavaScript to handle form submissions, simulate API calls, and dynamically render content. By the end of this lesson, you will be able to create a more interactive and engaging application that responds to user input in real-time.

Reviewing the Project Structure

Before we dive into linking JavaScript to our HTML, let's focus on the specific file we are creating and its location within the project structure.

app/
├── main.py
├── travel_planner/
├── static/
│   └── js/
│       └── travel-planner.js  # JavaScript file for enhancing interactivity
└── templates/
    └── index.html

We are creating the travel-planner.js file inside the static/js/ directory. This file will contain the JavaScript code responsible for enhancing the interactivity of our travel planner application. By placing it in the static/js/ directory, we ensure that it is served correctly by Flask as a static asset, allowing us to link it to our index.html file for client-side functionality.

Linking JavaScript to HTML

Now that we have created the travel-planner.js file in the static/js/ directory, it's time to link this JavaScript file to our HTML page. This is done by including a <script> tag in the index.html file. In Flask, we use the url_for function to correctly reference the static JavaScript file. This ensures that our JavaScript code is loaded and ready to enhance the page's functionality.

Here's how your index.html file should look, with comments indicating where the rest of the code should be:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Travel Planner</title>
</head>
<body>
    <!-- Form for trip planning... -->

    <!-- Results Section... -->

    <!-- Link to the JavaScript file for handling form submission and rendering results -->
    <script src="{{ url_for('static', filename='js/travel-planner.js') }}"></script>
</body>
</html>

This line of code is placed just before the closing </body> tag in your HTML file, ensuring that the JavaScript is loaded after the HTML content. By linking the JavaScript file, we enable the dynamic features and interactivity that will enhance the user experience of our travel planner application.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal