Flask is having trouble loading images within the static directory

I am facing an issue with loading two images in my HTML when the 'next' button is clicked. Initially, everything was working fine before I integrated the front end with Flask. The CSS and JS files are functioning properly, but the images are not loading as expected. On clicking the button, the JS is supposed to replace the old HTML in the main div with the new content containing the images, as defined in the update() function. All the JS, CSS, and images are stored in the static folder. Any suggestions or assistance would be highly appreciated. Additional information: I am receiving a 404 error indicating that the images cannot be located in a folder named Images, even though I have specified the static folder as the location. You can access the GitHub repository here: https://github.com/ewanh26/Web-App Code:


    main.py:
    
    from flask import *
        
    app = Flask(__name__)
        
    @app.route("/")
    def index():
        return render_template('index.html')
        
    if __name__ == '__main__':
        app.run(debug=True)
    
    index.js:
    
    <!-- language: lang-js -->
    
        let pageCounter = 0;
        let maxPages = 5
    
        const $prevButton = document.getElementById('prev')
        const $nextButton = document.getElementById('next');
        const $div = document.getElementById('maindiv')
    
        function update() {    
            switch (pageCounter) {
                default:
                    $div.className = 'slide1Header';
                    $($div).html("<h1>THE WORLD OF TOMORROW. WHAT'S NEXT FOR US?</h1>");
                    break;
                case 1:
                    $div.className = 'slide2';
                    $($div).html(`
                    <img src="{{ url_for('static', filename='starry.jpg') }}" alt="stars" id="starimg">
                    <img src="{{ url_for('static', filename='moon.png') }}" alt="moon" id="moonimg">
                    `);
                    break;
            }
        }
    
        update();
    
        $prevButton.addEventListener('click', function () {
            if (pageCounter > 0) {
                pageCounter--;
                console.log(pageCounter);
                update();
            }
        });
        $nextButton.addEventListener('click', function () {
            if (pageCounter < maxPages) {
                pageCounter++;
                console.log(pageCounter);
                update();
            }
        });
    
        window.addEventListener('scroll', function () {
            document.body.style.setProperty('--scroll', window.pageYOffset / (document.body.offsetHeight - window.innerHeight));
        });
    
    style.css
    <!-- language: lang-css -->
    
        html, body {
            font-family: Cambria, Cochin, Georgia, Times, 'Times New Roman', serif;
            margin: 0;
            padding: 0;
            height: 100%;
            width: 100%;
        }
        .slide1Header {
            display: flex;
            justify-content: center;
            align-items: center;
            position: fixed;
            font-style: italic;
            width: 100%;
            height: 100%;
            background: linear-gradient(-45deg,
            #bd33c4,
            #DE498E, 
            #FF5F58, 
            #FC9144, 
            #f8c330e1, 
            #FBAB19, 
            #FD9301, 
            #FE4A2B, 
            #FF0055
            );
            background-size: 2000% 2000%;
            animation: backgroundChange 15s ease infinite;
            transform: none;
        }
        .slide2 {
            background: black;
        }
        #starimg {
            display: block;
            width: 50%;
            margin-left: auto;
            margin-right: auto;
    
        }
        #moonimg {
            display: block;
            width: 30px;
            height: 30px;
            top: 17px;
            right: 33%;
            left: 66%;
            position: absolute;
            filter: brightness(5);
            filter: contrast(0);
            filter: blur(0.7px);
            filter: opacity(0.95);
            animation: moonScroll 0.5s linear infinite;
            animation-play-state: paused;
            animation-delay: calc(var(--scroll) * -1s);
            transform: rotate(-40deg);
            transform-origin: 0px 500px;
        }
        #moonimg::before {
            transform: rotate(-30deg);
        }
        button.prev, button.next {
            border-radius: 8px;
            position: fixed;
            transition-duration: 0.4s;
            border-color: white;
            border-style: none;
            padding: 4pt;
        }
        button.prev {
            left: 5%;
            bottom: 5%;
        }
        button.next {
            right: 5%;
            bottom: 5%;
        }
        .prev:hover, .next:hover, .prev:focus, .next:focus {
            background-color: #ff245b;
            color: white;
            outline: none;
        }
        @keyframes backgroundChange {
            0% {
                background-position: 0 50%;
            }
            50% {
                background-position: 100% 50%;
            }
            100% {
                background-position: 0 50%;
            }
        }
        @keyframes moonScroll {
            from {
                transform: rotate(0deg);
            }
            to {
                transform: rotate(-90deg);
            }
        }
    
    index.html
    <!-- language: lang-html -->
    
        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8">
                <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
                <!--<link rel="preload" as="image" href="{{ url_for('static', filename='starry.jpg') }}">
                <link rel="preload" as="image" href="{{ url_for('static', filename='moon.png') }}">!-->
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
                <title>The Future</title>
            </head>
            <body>
                <div id="maindiv"></div>
                <button class="prev" id="prev">← Previous</button>
                <button class="next" id="next">Next →</button>
                <script src="{{ url_for('static', filename='index.js') }}"></script>
            </body>
        </html>
    
    index.js
    
        let pageCounter = 0;
        let maxPages = 5
        
        const $prevButton = document.getElementById('prev')
        const $nextButton = document.getElementById('next');
        const $div = document.getElementById('maindiv')
        
        function update() {    
            switch (pageCounter) {
                default:
                    $div.className = 'slide1Header';
                    $($div).html("<h1>THE WORLD OF TOMORROW. WHAT'S NEXT FOR US?</h1>");
                    break;
                case 1:
                    $div.className = 'slide2';
                    $($div).html(`
                    <img src="{{ url_for('static', filename='starry.jpg') }}" alt="stars" id="starimg">
                    <img src="{{ url_for('static', filename='moon.png') }}" alt="moon" id="moonimg">
                    `);
                    break;
            }
        }
        
        update();
        
        $prevButton.addEventListener('click', function () {
            if (pageCounter > 0) {
                pageCounter--;
                console.log(pageCounter);
                update();
            }
        });
        $nextButton.addEventListener('click', function () {
            if (pageCounter < maxPages) {
                pageCounter++;
                console.log(pageCounter);
                update();
            }
        });
        
        window.addEventListener('scroll', function () {
            document.body.style.setProperty('--scroll', window.pageYOffset / (document.body.offsetHeight - window.innerHeight));
        });
    

Answer №1

Resolved the issue on my own by utilizing the standard file path instead of generating a URL with url_for() in the javascript file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Memory Exhausted: MongoDB and JavaScript running out of memory

Dealing with a massive amount of data in the telemetry table is proving to be a challenge. I keep encountering the dreaded "JavaScript heap out of memory" error. How can I tackle this issue? const connectionUrl = `mongodb://${userName}:${pwd}@${host}:${ ...

The error message "Unable to push property in an undefined array" is displayed when attempting to push a property into

I'm struggling to debug the error message TypeError: Cannot read property 'push' of undefined. The following code snippet is what's causing the problem: const parent_lead_contact = this.props.parentLeads?.filter((lead) => lead. ...

What is the best way to send progress updates from PHP to the webpage following a user's button press?

As a user clicks on a series of buttons on the page, it triggers a PHP script through jQuery utilizing the .ajax() method. Currently, I am appending a concatenated string dump of "progress updates" to a status placeholder DIV using the success: function(da ...

Tips for updating a row in a table after receiving updated data through ajax in an MVC application

I have a data table with Add, Edit, and Delete options. When new data is added to the table, I append a new row based on the response. GetServerData("Supplier/AddSupplier/", Supplierdetails, function (data) { if (data != null) { var row = "" ...

Add numerous submit buttons within a form. Upon clicking on a button, the form should be submitted to a specific URL using AJAX

I have a form with two submit buttons: one labeled as "SUBMIT" and the other as "SCHEDULE NEXT ROUND". When a user clicks on the "SUBMIT" button, the form values should be stored in the database and redirect to the view page. If they click on the "SCHEDULE ...

Utilizing Axios to filter response.data in an API request

Looking to retrieve the latest 8 products based on their date? Take a look at the code snippet below: const newestProducts= []; axios.get("http://localhost:3003/products").then(response => { let products = response.data.sort(fu ...

Highcharts gauge removing unnecessary white borders

I have created a highchart gauge code that looks great on JSFiddle, but when I paste it into my website, the 'border' options (borderColor and borderWidth) don't seem to work. The browser automatically adds white borders to my series, toolti ...

Transferring information from Vue Component to Vuex storage

I am currently working with a Laravel API route that looks like this: Route::get('c/maintenances/{contractor_user_id}', 'Maintenance\Api\ApiContractorMaintenanceController@index'); The contractor_user_id parameter is dynamic ...

I am facing issues with my Bootstrap and CSS conflicting with each other in React JS

My styles are mysteriously changing when I add the bootstrap link between the <head></head> tags. Here is the header without the bootstrap link: https://i.sstatic.net/ly2nf.png And here is the header with the bootstrap link: https://i.sstatic ...

Submitting the $_SESSION variable with HTML

Hi there, I hope everyone is doing well. I think I may have worded the title incorrectly, so I apologize for any confusion. Here is the code I'm working with: <form method="POST" action="checkoutManager.php" name="submitOrder"> <?php if(is ...

Exploring creative methods for incorporating images in checkboxes with CSS or potentially JavaScript

Although it may seem like a basic question, I have never encountered this particular task before. My designer is requesting something similar to this design for checkboxes (positioned on the left side with grey for checked boxes and white for unchecked). ...

Rearrange the characters within the variable before inserting them after

I'm currently dealing with an external system that generates outdated code, however, I do have access to css and javascript. The specific issue at hand involves working with a table that displays each item on a separate row, sometimes resulting in up ...

A Vue filtering feature that consistently adds 5 additional elements upon each use

I was wondering, how can I create a computed property filter function that always adds 5 more elements to the current array? Here are more details: Template: <span class="box-content" v-for="item in activeItems" :key="item.id"> <img class=" ...

Tips for positioning text within a div element's bottom edge

I'm facing a challenge in creating a footer for a div element that contains a <p> tag. The issue arises when the font size varies, causing the footer to extend outside the box. How can I ensure that it aligns at the bottom of the page with the c ...

SQL message comparison error within mysql module is malfunctioning

Currently, I am utilizing the nodejs MySQL module to automatically create a table every month. To ensure this process runs smoothly, I need to check if the table already exists using the condition err.sqlMessage == Table 'tableName' alre ...

Using jQuery to dynamically include a validation rule in numerous textboxes

Currently, I am working on dynamically adding a validation rule to multiple textboxes. Below is the JavaScript code I am using: //validate form. $("#SubmitForm").validate(); $("input[id*=Hours]").rules("add", { ...

Combining cells through the utilization of JavaScript

I've searched for ways to merge cells in a table using JavaScript but haven't been able to find any code that works. Is there a specific approach I can follow to implement cell merging like in MS-WORD tables? Your advice would be greatly apprec ...

Enhance your Vue app with filtered categories using Vue-google-chart

What is the process for creating a filter category in a bar chart using the vue-google-charts wrapper in Vue.js? I have successfully created a stacked bar chart and now I am looking to add a filter by label inside the legend. Here is my vue application: ...

What is the best way to validate the accuracy of an HTML form response by using PHP through $.post, all while keeping the answer confidential?

Currently, I am working on a fill-in-the-blank quiz. In my PHP file named index.php, my objective is to validate the user's input against the correct answer stored in my MySQL server. One approach I considered was to simply echo the answer using < ...

What is the best way to design a group of radio buttons with corresponding labels at the top

I'm looking to create a structure like this in HTML: https://i.sstatic.net/wLcZs.png Does anyone know how I can achieve this layout so that the labels are aligned properly with the radio buttons? My main challenge is getting the horizontal labels ab ...