Is it possible for me to determine when all images have finished loading in order to update the isLoaded variable to true?

I am using the template below:

<template>
    <div v-if='isLoaded'>
        <div @click='selectSight(index)' v-for='(sight, index) in sights'>
            <img :src="'https://maps.googleapis.com/maps/api/place/photo?maxwidth=300&photoreference=' + sight.photos[0].photo_reference + '&key='">
        </div>
    </div>
</template>

Is it possible to detect when all images have loaded in this template so that I can toggle isLoaded to true once they are all loaded? My goal is to prevent displaying the entire div until everything has been loaded to avoid flickering of loading images (some load faster than others).

<script>
    export default {
            data(){
                return {
                    sights: null,
                    isLoaded: false
                }
            },
            mounted() {
                axios.get('/getSights/' + this.lat + '/' + this.lng + '/' + this.type + '/' + this.range)
                .then(response => {
                    this.sights = response.data.result.results
                    this.nextPageToken = response.data.result.next_page_token
                }).catch((error) => console.log(error));
            }
    }
</script>

I attempted the following approach:

var images = document.getElementsByClassName('sight-photos');
images.onload = function () {
    console.log('hey')
}

However, I did not see the console message. I also tried this:

var images = document.getElementsByClassName('sight-photos')[0];
images.onload = function () {
    console.log('hey')
}

With this, I was able to see the message, leading me to believe that onload cannot be used on a collection of images. Is there another way to achieve this?

Answer №1

When utilizing the v-if directive, the element will not be created and subsequently the image will not load. An alternative approach would be to make use of the v-show directive on the div, which generates the HTML but keeps it hidden. One strategy could involve utilizing an array to monitor all loaded images, updating the isLoaded property accordingly.

<template>
<div v-show='isLoaded'>
    <div @click='selectSight(index)' v-for='(sight, index) in sights'>
        <img 
          :src="'https://maps.googleapis.com/maps/api/place/photo?maxwidth=300&photoreference=' + sight.photos[0].photo_reference + '&key='"  
          v-on:load="setLoaded(index)"
         >
    </div>
</div>

<script>
export default {
        data(){
            return {
                sights: null,
                loadedSights: []
                isLoaded: false
            }
        },
        mounted() {
            axios.get('/getSights/' + this.lat + '/' + this.lng + '/' + this.type + '/' + this.range)
            .then(response => {
                this.sights = response.data.result.results
                this.nextPageToken = response.data.result.next_page_token
                this.loadedSights = this.sights.map(function(){ return false; });
            }).catch((error) => console.log(error));
        },
        methods: {
            setLoaded: function(index){
                this.loadedSights[index] = true;

                for (var i=0; i< this.loadedSights.length; i++){
                    if (!this.loadedSights[i]){ 
                        this.isLoaded = false;
                        return  
                    }
                }
                this.isLoaded = true;
            }
        }
}
</script>

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

Having trouble extracting the date modified from a JSON file

I am able to retrieve section name, URL, web title, and headline from parsing JSON data with this code snippet. However, I seem to be encountering an issue where I cannot extract the last modified date. Here is the JSON structure: { "response":{ ...

Divide the MySQL results into two distinct groups and display them in separate div

I have a MySQL query that fetches all the topic results. I have also implemented a pagination system where the results are divided into pages, and the query's limit #,# varies depending on the current page. My goal is to organize these results into t ...

How does React-router handle component reloading when there is a change in the state of the parent component

Within my React application, I've integrated a ResponsiveDrawer component sourced from material-ui's demo. This component essentially displays a drawer containing a list of menu items, a title bar, and a content frame. The state of the component ...

applying a blur effect to the Vue modal mask

Trying to incorporate a blur panel behind my modal using vue.js, however, The issue arises when the modal-mask contains nested content. This makes it challenging to apply the filter: blur() property without blurring everything. Currently, I am only able t ...

Oops! The Vue router has encountered a RangeError due to exceeding the maximum call stack

I'm currently working on implementing a login feature using Vue.js. Initially, I started with the following code: However, encountered an error message stating "Range Error: Maximum call stack size exceeded." ...

Can one access the method definition within a Visual Studio Code setup for an AngularJS project?

I'm on a quest to locate the method definition within my AngularJS project, but alas, I am struggling to discover a quick and easy shortcut for this task. My attempts with Ctrl + Click only led me to the initial occurrence of the variable's decla ...

Enable the event listener for the newly created element

I am attempting to attach an event listener to this HTML element that is being created with an API call handleProducts() function handleProducts() { var display = document.getElementById("display") var url = "http://127.0.0.1:800 ...

Ways to retrieve a designated object linked to a specific value within a JavaScript structure

I am facing a challenge where I need to set a javascript property object with values from another property object within the same instance. Currently, I have the following object: var PLAYER = { slides: { { slide_id: 60, slide_content: 'c ...

Error: Attempting to assign a value to the property 'running' of an undefined variable

While working with Nuxt.js, I encountered an issue related to reading the running property of my client object. Here is the HTML code snippet: <b-button v-show="!(projectSelecter(project.ID)).isStarted" //this work just fine variant="success" c ...

Associate the callback function with a directive that does not have an isolated scope

Ensuring the correct context when binding a callback function to a directive is crucial. When working with an isolated scope, this task is easily accomplished. <bar-foo callback="mycontroller.callback()"></bar-foo> The directive code: ... ...

Progressively modifying related elements over time intervals

I have a specific list of p elements in my HTML code that I need to modify sequentially with a time interval of 1 second. Here is the HTML: <p>Changing first sentence!</p> <p>Second sentence ready!</p> <p>Third one coming up ...

Fetch operates based on the specified categoryId

Hey there, I'm currently in the process of learning JS and trying to fetch data from an API. I've successfully fetched all the work from api/works and displayed them in a div. Now, I'm looking to create 3 buttons that represent 3 categories ...

Attempting to parse a file using JSON.parse

I'm currently in the process of downloading a file and attempting to utilize JSON.parse. The result should be { dateTime: "2012-04-07T17:15:00.000-05:00", value: "1065.91" }. Can someone verify if I am passing the correct object through JSON.parse and ...

What are some strategies I can implement to effectively manage different errors and ensure the app does not crash

I came across a variety of solutions for error handling. The key concept revolves around this explanation: https://angular.io/api/core/ErrorHandler Attempts were made to implement it in order to capture TypeError, however, the outcome was not successful: ...

Enable the ability to input a value of -1 by clicking on a button or link, but only allow it once (the first click) without needing to disable the button or

I am working with the following script: <script language=javascript> function process(v){ var value = parseInt(document.getElementById('v').value); value += v; document.getElementById('v').value = valu ...

The resolve in Angular UI-Router is not being properly injected into the controller

As a Java developer venturing into the world of Angular and Express, I am encountering challenges along the way. To gain hands-on experience, I am attempting to create a small application using these technologies. The Goal: I have provided a password rese ...

Tips for preventing useEffect from triggering a route?

Recently delving into reactjs, I stumbled upon a situation in the code where the route alerts messages twice. I'm seeking advice on how to prevent this issue, please disregard the redux code involved. Any suggestions? Index.js import React from &apos ...

Encountering issues with loading styles in Vue single file components

While working on my project at this link, I encountered an issue with displaying a styled modal. Despite trying to import the styles using: <style scoped> @import "../styles/modal-style.css"; </style> and even directly pasting the co ...

Display the size of the data array in VueJS once the data has been retrieved from the API

Using Vue JS, I have been attempting to retrieve data from an API. My goal is to determine the length of the array and then log it to the console using a method. However, every time I try to do this, the value logged is always "0" instead of the actual le ...

"Experiencing a problem with Next.js 13 where the User Context is not functioning properly outside of _app

When using Next.js 13 and the user context, I've noticed that it doesn't function properly outside of _app.tsx. Any idea why? src>context>UserPositionContext.tsx import { createContext, useContext, useState } from "react"; const ...