How can I load only specific images on a webpage using HTML?

I attempted to implement an image filter for my website by using the code below:

<script>
function myFunction() {
// Initialize variables
var input, filter, ul, li, a, i;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("searchColumns");
li = ul.getElementsByTagName('figure');
if (filter==""){
  li[i].style.display = "none";
}
else{
  for (i = 0; i < li.length; i++) {
      a = li[i].getElementsByTagName("figcaption")[0];
      if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
          li[i].style.display = "inline-block";
      } else {
          li[i].style.display = "none";
      }
 }  }
}
</script>

However, the issue I encountered is that all of the 200+ images are loading on startup, resulting in a delay. Is there a method to prevent them from loading until they are filtered?

Answer №1

Is this operational?

function searchFilter() {
    var input = document.getElementById('searchInput').value.toUpperCase(),
        list = document.getElementById("filterItems"),
        items = list.getElementsByTagName('div');
        
    if (input == "") {
        list.style.display = "none";
    } else {
        for (var j = 0; j < items.length; j++) {
            var b = items[j].getElementsByTagName("h3")[0];
            if (b.textContent.toUpperCase().indexOf(input) !== -1) {
                items[j].style.display = "block";
            } else {
                items[j].style.display = "none";
            }
        }
    }
}

Answer №2

Thanks to the assistance of @A.Zaima, I was able to resolve this issue. I structured an array containing all the image URLs and another holding their respective names. Here is the code snippet that solved the problem:

var input, filter, link, i;
input = document.getElementById('searchInput');
filter = input.value.toUpperCase();
if (filter!=""){
  for (i = 0; i < names.length; i++) {
      link = names[i];
      if (link.substring(0, filter.length)==filter) {
          var figure = document.createElement("FIGURE");
          var img = document.createElement("IMG");
          var figcaption = document.createElement("FIGCAPTION");
          var textnode = document.createTextNode(names[i]);
          figcaption.appendChild(textnode);
          img.src = links[i];
          document.getElementById("searchResults").appendChild(figure);
          figure.appendChild(img);
          figure.appendChild(figcaption);
      }
    }
  }
}

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

Conceal a component when the succeeding one appears on a separate line

I'm looking for a solution to display an address on a webpage in two different formats based on the length. The first format should be: Street Number, PostalCode City If the address is too long to fit on one line, it should be displayed as: Street ...

Error: The Google Translate key is not found in the Node.js AJAX request

I have a basic Node.js script that functions properly when executed locally in the terminal: exports.google_translate = function (translate_text, res) { var Translate = require('@google-cloud/translate'); var translate = new Trans ...

Issues with data within a Vue.js pagination component for Bootstrap tables

Currently, my table is failing to display the data retrieved from a rest api (itunes), and it also lacks pagination support. When checking the console, I'm encountering the following error: <table result="[object Object],[object Object],[object Ob ...

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...

Angular: merging multiple Subscriptions into one

My goal is to fulfill multiple requests and consolidate the outcomes. I maintain a list of outfits which may include IDs of clothing items. Upon loading the page, I aim to retrieve the clothes from a server using these IDs, resulting in an observable for e ...

Choose components identified by a dot

If I have a simple script that displays an element based on the option selected, how can I handle periods in the values? For instance: <select id="my-selector"> <option value="cat.meow">Cat</option> <option value="dog.bark"> ...

Extract the text from an html element by utilizing xpath

This snippet contains HTML content <p class="ref Hover"> <b class="Hover Hover Hover Hover Hover">Manufacturer Part Number:</b> MC34063ADR2G<br> <b>Mounting Method:</b>&nbsp; Surface Mount& ...

Converting HTML code into executable PHP code

I'm having trouble embedding PHP into an HTML file. I modified my .htaccess to recognize HTML files as PHP, but when I attempt to open the .html file in my browser, it gets downloaded instead of being processed and shown. UPDATE: Here is what's ...

When programming with PHP and JavaScript, managing events' start dates and end dates

In my current project, I am developing a script that deals with events. An event is scheduled to start on 12/02/2016 at 11:20 and end on 01/04/2016 at 8:20. When the end date is reached, I need to trigger a specific action using JavaScript. if (t.getFullY ...

Error Handling in ReactJS

Every time I try to execute my ReactJS code, an error pops up saying: Unhandled Rejection (Error): Material-UI: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="90e2f5f1f3e4d0a1a6bea3bea0">[email protected]</a> ve ...

External API data is shown in the browser console but appears as undefined on the page

Can you please lend me a helping hand? I am facing a critical issue while attempting to retrieve data from an external API using axios in NextJS (Reactjs)/TypeScript through getServerSideProps. The data fetching is successful, and the JSON is returned on t ...

Implementing jQuery to showcase an element on the screen

I would like to express my gratitude to everyone who has helped me. Please forgive my poor English :) Can someone provide me with a jQuery script that can extract the name of the currently selected tab and display it in an h1 tag? Whenever the selected ta ...

Removing a dynamic component in Angular

Utilizing Angular dynamic components, I have successfully implemented a system to display toaster notifications through the creation of dynamic components. To achieve this, I have utilized the following: - ComponentFactoryResolve - EmbeddedViewRef - Ap ...

Is there a one-liner to efficiently eliminate all instances of a specific sub-string from an array using the filter

In search of a solution to filter an array and eliminate all instances of substrings, similar to removing entire strings as shown below: const x = ["don't delete", "delete", "delete", "don't delete", "delete", "don't delete"] x= x.filter(i ...

What is the best way to change a byte array into an image using JavaScript?

I need assistance converting a byte array to an image using Javascript for frontend display. I have saved an image into a MySQL database as a blob, and it was first converted to a byte array before storage. When retrieving all table values using a JSON ar ...

Embracing the Quirks of JSON: A Call for a

Currently, I am in the process of developing a webpage that involves incorporating four distinct JSON entities (objects, arrays). Excuse my lack of appropriate jargon. Upon receiving the JSON data, it is structured as an object with numerous sub-objects, ...

Is there a way to turn off vue.js transitions specifically for testing purposes?

I'm utilizing a vue.js component with the <transition> element for show/hide animations. However, I want to disable the animation for faster testing. How can I achieve this? The solution proposed is * { transition: none !important } in this lin ...

What is the best way to call a method within a TypeScript class using its name as a string while already inside the class itself?

Currently, I am developing a class that automates the creation of routes for Express and invokes a function in a controller. However, upon trying to execute this[methodName](req, res), I come across an error message stating: 'Element implicitly has an ...

I'm struggling to understand how to interpret this. The v-tab function seems to be generating a button with various properties, but I'm unsure which specific property is related to

The V-tab below generates the button known as the right one on the v-app-bar: https://i.stack.imgur.com/DzNmq.png <v-tab :to="'/demo'" active-class="text--primary" class=&quo ...

Unable to adjust the text color to white

As someone who is new to Typescript, I'm facing a challenge in changing the text color to white and struggling to find a solution. I'm hoping that someone can guide me in the right direction as I've tried multiple approaches without success ...