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

Tips for handling a multi-step form in React?

Below is the code snippet for the multistep form I have been working on: import clsx from 'clsx'; import React from 'react'; import PropTypes from 'prop-types'; import { makeStyles, withStyles } from '@material-ui/styles ...

Interactive Audio Progress Bar in HTML5

Hello, I am trying to create a simple HTML 5 player with controls for play and pause. However, I am having trouble implementing a progress bar that interacts with the music time. I found an example of an interactive progress bar here: http://jsfiddle.net/ ...

Add the AJAX response to a div element when the submit button is pressed

Working on a WordPress project involving an AJAX call, I need to return the result of a row to a div with the ID #hero. The challenge is that since the result is inside a for loop and each row has its own hero div, I want the result to be returned to the c ...

Utilizing a variable name as an object key in TypeScript

Can this be achieved? static readonly statusMapping: { [key in UploadStatus]: PopupMessageStatus } = { UploadStatus.COMPLETED : PopupMessageStatus.COMPLETED } UploadStatus is an enum with numeric values, where UploadStatus.COMPLETED = 0 p ...

What is the best way to have the sidebar of a webpage slide out over the main body content that is being displayed?

Issue Summary I am experiencing an issue with the positioning of my sidebar, which is initially located 66% offscreen using -translate-x-2/3. The sidebar is meant to be pulled into view onmouseover, however, the main body content remains stuck in place. I ...

What is the best way to merge all project modules into a single file using the r.js optimizer?

While working with the r.js optimizer, I noticed that the final index.html file doesn't seem to allow for referencing just a single script without making any async calls to other scripts during a user's session. It appears to generate multiple gr ...

What could be causing a momentary 404 error when I click on a next.js `Link` that connects to an API endpoint before redirecting to the intended page?

Hello there, I recently followed a tutorial on adding authentication with Passport to Next.js from this resource: https://auth0.com/blog/next-js-authentication-tutorial/ However, I encountered a minor issue. When I click the "/login" Link in my Next.js ...

Searching for a specific data point within the latest entry of a JSON file using Javascript

I am currently in the process of utilizing a sensor to measure temperature, which is then stored in a mongo database. This data can be accessed as a JSON file by visiting ('/data'). My goal is to determine the latest entry and extract the temper ...

Limit the precision of decimal number output to a specific value

I need assistance with achieving the output 999999.35 in angular or javascript combined with html. I am looking to restrict the number of 9's to a maximum of 6 digits before the decimal point, and after 6 digits it should not accept any more digits. A ...

Rendering SVG graphics on browsers for Android devices

I've been struggling with an issue for quite some time now and I can't seem to find a solution. The problem lies in having an SVG image as a CSS background on the top left corner of a div. Instead of seamlessly merging with the div background, i ...

HTML: Align DIV contents next to each other without any overlap

Below are three boxes displayed. Boxes 1 and 3 appear fine, but in box 2 the text content is overlapping. The issue lies with the <div> having the class .vertical_center.grade_info which has a specific margin-left of 100px, causing the overlap. I ne ...

Choosing a single item from multiple elements in React using React and typescript

In this particular project, React, TypeScript, and ant design have been utilized. Within a specific section of the project, only one box out of three options should be selected. Despite implementing useState and toggle functionalities, all boxes end up bei ...

Is there a way to dynamically import several CSS files in React Native depending on the data stored in this.state?

How can I dynamically import multiple CSS files in a React Native project based on language? import React, { Component } from "react"; if(this.state.language === "he"){ import styles from "./he"; }else{ import styles from "./en"; } I attempted the ab ...

Halt hovering effect after a set duration using CSS or Vanilla JavaScript

Looking for a way to create a hover effect that lasts for a specific duration before stopping. I want the background to appear for just 1 second, even if the mouse remains hovering. Preferably using CSS or JavaScript only, without jQuery. To see my curren ...

I am experiencing issues with the HTTPClient call not returning accurate JSON data within my Appcelerator Titanium application

Every time I attempt to retrieve information from a JSON file, I encounter an error. function search(e){ var url = 'https://www.dotscancun.com/createjson.php?id=100001'; var xhr = Ti.Network.HTTPClient({ onerror: function(e){ ...

The issue of passing state in React Router v4 Redirect unresolved

I have a specific private route, /something, that I only want to be accessible when logged in. I've used Redirect with the state parameter set, however, when I try to access it at the destination, location.state is showing as undefined. Here is how I ...

Troubleshooting issue with file upload feature in Angular for Internet Explorer 9

I have implemented a file upload method using the following code: <input type="file" name="upload-file" ng-model= "excelFile" accept=".xlsx" onchange="angular.element(this).scope().fileChanged(this);" ...

Error importing React Icons with the specific icon FiMoreHorizontal

Currently following a guide to create a Twitter-like application and I need to add the following imports: import { FiMoreHorizontal } from 'react-icons/fi' 2.3K (gzipped: 1K) import { VscTwitter } from 'react-icons/vsc' 3.1K (gzipped: ...

Run a PHP function using <button onclick=""> tag

Is it possible to trigger the execution of a PHP script when clicking an HTML button? I am aware that simply calling a PHP function directly from the button's onclick event like this: <button onclick="myPhpFunction("testString")">Button</butt ...

How can I obtain the download link for an image that has been resized using Node.js in Google Cloud Functions?

I have recently started exploring node js and google cloud functions. Successfully, I can resize an image to create a thumbnail. However, I am stuck at finding the download URL for the newly generated thumbnail. Below is the code snippet: exports.gener ...