Pre-fetching Images with Dynamic File Names in JavaScript

I run a website packed with HTML videos featuring personally designed video control buttons. The dilemma arises when hovering over the play/pause button - CSS works its magic to swap out the button image for one in a different color. However, upon initial page load or reload, that first hover causes the button to disappear momentarily while it fetches the new image. To counter this, I decided to preload images labeled numerically starting from one. Each thumbnail follows a consistent naming convention: a number followed by 'mo.png'. It goes like 1mo.png, 2mo.png, and so on. My solution involved automating the preloading process using this snippet:

for(var x = 1; x < 5; x++){
    no = x.toString();
    cs = 'img' + no + ' = new Image(); img' + no + ".src = 'media/" + no + "mo.png';";
    eval(cs);
}

This method does the job for images following the pattern of 1mo.png to 4mo.png (alterable based on how many 'mo'-suffixed pictures to preload).

My desire is for JavaScript to scour through my directory's images folder and replicate the same approach used for 'mo' images to preload any images present with assorted names. Essentially, I seek insight on extracting file names from a specific folder within my site's directory and storing them as an array or variables.

Answer №1

When using client-side Javascript in the browser, it is important to note that direct access to your server's directories is not possible. Server-side languages like Node.js, Ruby, Python, and PHP are better suited for parsing files and directories.

To retrieve folder contents and avoid cross-site scripting errors, consider setting up a script in your preferred language that returns data as jsonp. This can then be called from other domains by making an ajax request in Javascript.

If you are interested in similar topics, there is a related question on StackOverflow:

list all images in directory in JSON

Additionally, here is a helpful PHP function example:

print_r(scandir('/var/www/yoursite.com/media'));

For more information on the scandir function in PHP, refer to the official documentation: http://www.php.net/manual/en/function.scandir.php

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

translucent three.js texture with shader material

I'm currently using a circular texture to display particles: The circle texture contains transparent pixels. I'm leveraging ShaderMaterial and BufferGeometry to assign custom sizes and colors to each node. However, I'm encountering issues w ...

Generates a dynamic HTML table using JSON data through JavaScript

I need help organizing my json data into a dynamic HTML table with customizable headings. If there is no value for a particular item, the box should remain empty. [ { "name":"value1", "email":"<a hr ...

struggling to correctly display json api data in javascript onto html

I am receiving a json API response from my JavaScript request. I can successfully print the output to the console and it appears properly formatted like this: { "id": "1", "name": "John" } However, when I try to display it on an HTML page, it looks l ...

Turning away swiftly from a popover triggered by hovering does not automatically conceal the popover

When utilizing hover-triggered popovers for specific highlighted rows within a table, I noticed an issue. If you scroll away quickly using the mouse wheel, the popover remains visible for an extra second even though you are no longer hovering over the targ ...

Is it possible to connect to a Node server from outside the network if the application is only listening on 'localhost'?

When utilizing the Express framework and we implement app.listen(port), the app will be located at localhost:port/ On a local machine, it is clear how to access this address using a local browser running on the same machine. Even clients within the same n ...

What are the various jQuery methods that can be utilized in the object parameter of a jQuery element creation request?

According to a post by John Resig on his website at http://ejohn.org/apps/workshop/adv-talk/#3, it is mentioned that methods can be attached using the object parameter. While 'text' appears to function correctly, any other content in the object ...

Arrange the 2D array in JavaScript by utilizing both categories

Looking to organize a 2D array based on two specific criteria: [ [ "the,", 3 ], [ "who,", 3 ], [ "take,", 4 ], [ "over,", 4 ], [ "world,", 5 ] ] Sort by number in ascending order Then arrange alphabe ...

Creating a Node.js/javascript assistant to set default values based on the typeof operator

It's becoming tiring to constantly write code like this: <% box_content = typeof box_content != 'undefined' ? box_content : ''%> <% box_class = typeof box_class != 'undefined' ? box_class : 'box'%> ...

How to style the background color of the selected option in a <select> element using

Is there a specific style I can use to change the color of a selected option in a dropdown menu? For example: <HTML> <BODY> <FORM NAME="form1"> <SELECT NAME="mySelect" SIZE="7" style="background-color:red;"> <OPTION>Test 1 &l ...

Sort the array elements by a specific property while preserving the original order of the array

I created a function that can group an array by one or more properties: var groupBy = function (fields, data) { var groups = {}; for (var i = 0; i < data.length; i++) { var item = data[i]; var container = groups; for (va ...

The issue of elements flickering while being hidden and shown with jQuery has been observed in both Chrome and

Having trouble with a simple animation using jQuery? While it may work smoothly in Firefox, you might be experiencing flickering in Chrome and Edge. Check out this jsfiddle for reference: HTML <div id="boxes-wrapper"> <div class="box"></ ...

Retrieve information from a controller and pass it to a Component in AngularJs

Having an issue with passing data from a controller to a component in AngularJs. The data is successfully passed to the template component, but it shows up as undefined in the controller! See below for my code snippets. The controller angular.module(&a ...

Attempting to position the text area and the button in a horizontal layout

https://i.sstatic.net/kZHF2.png <form class="container"> <div class="row"> <div class="col-md-5"> <h2>Template</h2> <textarea id="template" value={this.state.value1} place ...

What steps should I take to handle JSON data in my component's state if it's causing issues when I try to access the data within a variable

I am facing an issue where I am trying to extract data from my state and then integrate it into the config variable in order to display this data on highCharts. However, I keep encountering errors such as "Cannot read property 'SeriesDates' of un ...

Utilizing $ImageCacheFactory to preload all images

After creating a mobile application using the ionic framework with multiple images, I encountered an issue of flickering while loading them. To tackle this problem, I utilized $ImageCacheFactory for preloading all images as described in a helpful blog post ...

Exploring Bootstrap 4's Effects on the Heights of Various Elements

I find it difficult to explain what I want, so I created a mockup https://i.sstatic.net/2WHA7.png How can I achieve this layout using bootstrap 4? The goal is to have the four elements on the right always be equal in height (except on mobile) like the ele ...

What is the rationale behind using both useMemo and createSelector in this code?

This example from the React-Redux documentation showcases how a selector can be utilized in multiple component instances while depending on the component's props. import React, { useMemo } from 'react' import { useSelector } from 'reac ...

Change the background color of the right column and customize the container in Bootstrap to

I am looking to customize the background color of the second column in a way that it stretches to the full width of the screen, overriding the constraints of its container. Does anyone have a solution for this? <div class="container"> ...

Utilizing PHP to fetch data from a separate webpage

This is a question that has sparked my curiosity. I am not facing any particular issue that requires an immediate solution nor do I possess the knowledge on how to achieve it. I have been contemplating whether it is feasible to utilize PHP for fetching co ...

Refreshing data in an HTML table following a successful AJAX request

When utilizing AJAX to execute destructive operations on database tables such as insert, update, or delete, it is essential for the DOM to accurately reflect these changes. There are two commonly used methods to achieve this. If the destructive database o ...