Having trouble replacing/using a relative image URL with JavaScript. Absolute path is functional, but relative path is not working

I have included what I believe are the crucial aspects in the fiddle. Currently, all my files are stored in a single directory. The CSS assigns a background image to the #slides div using a relative path. Then, with the help of JavaScript and an array, I intend to change the background image. However, the script only functions if I input an absolute path for the image.

The fiddle does not showcase the images visually, but the structure is intact. Ordinarily, I possess a function that increments 'i' and exhibits the corresponding image; however, for troubleshooting purposes, I chose not to include it here.

The rationale behind utilizing relative paths is my potential need to duplicate the entire folder or access it from a USB drive on a PC lacking internet connectivity.

In the developer console, setting 'i = 1' and executing the function results in a blank background when relative paths are used. Conversely, with absolute paths set and following the same steps, the correct picture displays based on the value of 'i'.

Any assistance is greatly appreciated!

http://jsfiddle.net/xvs8ogjg/4/

HTML

<div id="slides"></div>

CSS

/* Although I utilize % based sizes in the actual version, everything else remains consistent. */

#slides {
    width: 200px;
    height: 200px;
    margin: 0;

    /* This CSS correctly displays the initial image upon page load */
    background-image: url("test1.svg");

    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
}

JS

// Array with images. Images, CSS, and JS are all housed within the slideshow directory for now.

var slides = document.getElementById('slides');

// Does not function
var images = new Array (
    "test1.svg",
    "test2.svg"
);

// Also ineffective - I attempted a workaround, unfortunately without success
var images = new Array (
    "../slideshow/test1.svg",
    "../slideshow/test2.svg"
);

// Operational
var images = new Array (
    "http://example.com/directory/slideshow/test1.svg",
    "http://example.com/directory/slideshow/test2.svg"
);

// Similarly functional, locally
var images = new Array (
    "file:///C:/Users/myname/directory/slideshow/test1.svg",
    "file:///C:/Users/myname/directory/slideshow/test2.svg"
);

var i = 0;

var change = function() {
    slides.style.backgroundImage = 'url("' + images[i] + '")';
};

Answer №1

The location where you request the file will determine its availability. Unfortunately, it is not possible to accurately comprehend your description based on the plunkr alone, as it is contingent on the specific plunker URL.

//My attempt at bypassing the system failed miserably
var images = new Array (
    "/directory/slideshow/test3.svg",
    "/directory/slideshow/test4.svg"
);

This script should function regardless of the domain location. I typically steer clear of using ../ in my URLs.

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

A missing semicolon is encountered while compiling a React application

I am currently working on my app using Create React App and incorporating scss. I have used a vscode plugin to convert the scss to css, but I keep encountering an error when running npm run build. The error message reads as follows: [email protected ...

Please submit the form to log in with your credentials

Here is the HTML code snippet for a form where users can enter their username and password to log in: <form Name ="form1" Method ="POST" ACTION = "userlogin.php" id="form1"> <div id="main_body" class="full-width"> <label>User ...

Do I need to include success as a parameter in my Ajax call even if my function does not return any values?

When an image is clicked, I trigger an ajax call. The image includes an href tag that opens a different page in a new tab upon click. The purpose of this ajax call is to record the user's clicks on the image for telemetry purposes in a database table. ...

The usage of Arrow Functions and Inheritance within TypeScript

Currently, I am immersing myself in TypeScript with the guidance of Barasat Ali Syed's Deep Dive. While exploring Arrow Functions and inheritance, I stumbled upon the following code snippet. Could you please assist me in comprehending the significanc ...

The react function is malfunctioning and not displaying a line break in this paragraph

After much searching and experimentation, I am still unable to create a new line in this React function. It seems like a basic issue, but as a newcomer, I would appreciate any advice. One suggestion was to use the following CSS: .new-line { white-space: ...

Transferring Data in Vue.js Components through Props

I've encountered an issue while trying to pass a prop from the main Vue instance to a component. While one of the props is being successfully passed, the second one seems to be causing some trouble. Main Instance var app7 = new Vue({ el: &apos ...

Next.JS - What is the reason behind data fetching occurring on both the server and client side?

When I call a regular fetch function in the index.js component and then log the response to the console, something unexpected happens. Despite the fetch being inside the component function, the response is also logged on the server side: it shows up in the ...

The video keeps shifting out of the second column in the row within the bootstrap layout

I'm having trouble positioning a video within a row on my webpage. I want the video to display as the second column in the row, aligning to the right of the page. However, it keeps appearing below the first column as if it's in a separate row. H ...

The sequence of error middleware in Express4

Encountered a series of code execution that seemed unusual. Here's the code snippet: server.js const Actions_Single_PVC = require('./routes/Actions_single_PVC.js'); app.use('/Actions_single_PVC', Actions_Single_PVC); app.use((e ...

Implementing real-time data visualization by dynamically updating a line graph on a website using information retrieved from a Java

Currently, I have a java application running on one PC and a web application consisting of javascript, html, and bootstrap hosted on a tomcat server on another PC. The java application includes two variables within a class - distance and time - that are c ...

Issue with vertical navigation bar

Currently working on creating a vertical navigation bar without any styling. It's challenging to figure out how to align the items properly side by side. You can check out the basic functionality at . When clicking on 'Android', I want the g ...

Problem encountered with Discord.js: the event handler function on('interactionCreate') is not functioning properly, but on the other hand, the event handler function on('messageCreate

Right now, I am tackling the commands for my bot and facing a bit of a roadblock. Whenever I implement the following code snippet: client.on('messageCreate', async interaction =>{ // somethingHappens }) Everything runs smoothly. However, wh ...

Issue: Unidentified supplier following JavaScript compression

Here is the AngularJS controller code that I am working with: (function() { 'use strict'; angular .module('app') .controller('TemplateCtrl', TemplateCtrl); function TemplateCtrl($http, $auth, $rootS ...

Chrome is able to interpret Behat CSS selectors, whereas Firefox struggles with them

Recently I began working with Behat and Selenium for website test automation. One issue I've encountered is that some CSS selectors work in Chrome but not in Firefox. For instance, in my Behat code: Then I press ".topmember-resultList .resultListIte ...

Refine radio button list based on input typed in text box

How can I filter my checkbox list based on letters typed into a textbox? The data for my checkbox list comes from a database. I attempted to do this using JavaScript, but it's not working. Is there a better way to achieve this functionality? <asp: ...

Missing entry in the dropdown menu rather than the intended selection

Within my HTML code, I am using the following structure: <div class="col-md-8"> @*@Html.DropDownList("templateTypes", (IEnumerable<SelectListItem>)ViewBag.TemplateTypes, new { @class = "form-control", ng_model = "currentTemplat ...

Guide on creating frozen columns in an Angular 2 table with the ability to scroll through multiple columns

Within my table, there are 3 columns that must always remain on the left side. Additionally, there is a column containing a grid where each element represents an hour of the day, requiring it to be scrollable. I have attempted various proposed solutions, ...

Issue encountered: The differ cannot recognize the provided object '[object Object]', which is of type 'object'. NgFor is limited to binding Iterables only

I have been following a tutorial on Ionic created by Paul Halliday, focusing on a shopping list project that utilizes Firebase and Angular. However, I am encountering an error every time I try to run the application: Error: Uncaught (in promise): Error: ...

Images in responsive design not adjusting size properly

In my current web standards design course, I am delving into HTML/CSS and focusing on making our websites more responsive this month. As part of the process, I have successfully converted all pixel units to percentages and changed all font sizes from pixel ...

What is the reason for Selenium only capturing a portion of the HTML content on a webpage?

I attempted to utilize selenium in order to navigate the web-untis webpage and locate any tests scheduled for this week, but I am facing difficulty in locating the web-elements within the html-file that contain the lesson data. Although other elements such ...