Modifying background image with Javascript

I've been working on developing a slideshow for one of the web pages I'm building. To achieve this, I set up a div with a unique class name that allows me to change the background image using JavaScript. Here's what I've accomplished so far:

  1. Identified the specific div where I want to switch the background image using querySelector
  2. Attempted to update the background image of that div using JavaScript

Despite debugging the function in DevTools, I'm still unable to figure out why the image isn't changing. Any insights on what might be going wrong? I've provided some code snippets below for reference. Appreciate any help.

HTML

<div class="content-one-right">
  <div class="inner-content-one-right">
    <div class="slideshow-container">
      <a class="prev" onclick="transitionSlides(-1)">&#10094;</a>
      <a class="next" onclick="transitionSlides(1)">&#10095;</a>
    </div>
  </div>
</div>

CSS

.content-one-right {
  grid-column: col-start 7 / span 6;
  height: 60vh;
}

.inner-content-one-right {
    height: 90%;
    width: 90%;
}

.slideshow-container {
    height: 100%;
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-image: url('../images/home-slideshow/home1.jpg');
    background-repeat: no-repeat;
    background-size: cover;
}

.prev, .next {
    cursor: pointer;
    color: #FFF;
    font-weight: bold;
    font-size: 1em;
    border-radius: 0 3px 3px 0;
}

.prev:hover, .next:hover {
    background-color: rgba(0,0,0,0.8);
}

JavaScript

var slideshowIndex = 0;

function transitionSlides(n) {

  var images = ["home1", "home2", "home3", "home4", "home5", "home6"];
  slideshowIndex += n;

  if(slideshowIndex < 0) {
    slideshowIndex = images.length-1;
  }
  else if (slideshowIndex >= images.length) {
    slideshowIndex = 0;
  }

  var getContainer = document.getElementsByClassName('slideshow-container')[0];
  var imageToChange = "url('../images/home-slideshow/" + images[slideshowIndex] + ".jpg')";

  getContainer.style.backgroundImage = imageToChange;

}

Answer №1

The issue may lie in the method you are employing to alter the background image. Initially, when you set it for the first time, it is done within the stylesheet using a CSS property.

Subsequently, when attempting to modify it using the .style property of the element, it proves ineffective as these methods differ. As stated on this page:

The style property does not provide a comprehensive view of the styles assigned to an element, only reflecting the CSS declarations established through inline styles rather than those derived from external style rules such as those present in the document's section or external style sheets.

To gain clarity, test this command in your console while on this current page:

document.querySelectorAll('input[type="submit"]')[3].style

This action targets the blue "Post Your Answer" button at the bottom of the page, featuring a clear blue background specified in the CSS. However, the CSSDeclaration object displayed in your console comprises solely of empty values because it exclusively represents the inline styles and not those applied via CSS.

Fascinating, isn't it? Armed with this understanding, I believe you can select between the two approaches to ensure your slideshow functions as anticipated. Perhaps avoiding the use of background images altogether might be simpler; opting instead for an img tag where JavaScript can be employed to configure the src attribute.

Answer №2

Encountering a familiar issue as shown in this thread. Valuable insights are available there. When experimenting with your code in JSFiddle, an exception is thrown: transitionSlides is not defined. It's advised to eliminate the onclick handler and utilize addEventListener() instead. While utilizing IDs for prev and next buttons is recommended, the following approach will suffice:

HTML:

<div class="content-one-right">
    <div class="inner-content-one-right">
        <div class="slideshow-container">
            <a class="prev">&#10094;</a>
            <a class="next">&#10095;</a>
        </div>
    </div>
</div>

JavaScript:

var slideshowIndex = 0;

document.getElementsByClassName('prev')[0].addEventListener("click", function() {
    transitionSlides(-1);
}, false);
document.getElementsByClassName('next')[0].addEventListener("click", function() {
    transitionSlides(1);
}, false);

function transitionSlides(n) {

    var images = ["home1", "home2", "home3", "home4", "home5", "home6"];
    slideshowIndex += n;

    if(slideshowIndex < 0) {
        slideshowIndex = images.length-1;
    }
    else if (slideshowIndex >= images.length) {
        slideshowIndex = 0;
    }

    var getContainer = document.getElementsByClassName('slideshow-container')[0];
    var imageToChange = "url('../images/home-slideshow/" + images[slideshowIndex] + ".jpg')";

    getContainer.style.backgroundImage = imageToChange;

}

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

Is it possible to extract the version_name using the version_code of an android package?

Is it possible to retrieve the version_name by using the version_code of an Android package? For instance: 'com.nianticlabs.pokemongo' version_code: 2017121800 => version_name: 0.87.5 I'm looking for a function that can accomplish th ...

jQuery alert: A TypeError was caught stating that the object being referred to does not have the 'dialog' method available

For a few days now, I have been tirelessly searching for a solution to this issue and it has caused me quite a bit of stress. My problem lies in echoing a JQuery popup script within php: echo '<link rel="stylesheet" href="http://code.jquery.c ...

Enhancing the appearance of React Native components by incorporating borderColor results in the emergence of

In my current React Native project, there is a profile component that includes the following design: https://i.sstatic.net/URrN6.png The profile container is styled with a backgroundColor of '#fff', and the pencil icon has a borderColor of &apo ...

What steps do I need to take in order to implement a basic ZeroClipboard copy-to-clipboard feature in jQuery on jsFiddle with just one click?

I'm having trouble implementing ZeroClipboard in a jQuery environment. My goal is to have the text within each div with the class copy copied when clicked. The following jsFiddle demonstrates the functionality with double click using the stable ZeroC ...

Invoking Javascript Functions using their names

Suppose I have the following element on my page... <span data-function="DoSomething">Click</span> ... and then add the following to my page header... $(document).ready(function() { $('[data-function]').each(function() { ...

Traverse the array of nested JSON objects in an iterative manner

I need to iterate through a JSON array object with the following structure: var myJSONObject = { "abc": { "prod_1": [ {"prod_ver" : "prod 1 ver 1"}, {"prod_ver" : "prod 1 ver 2"}, ], "prod_2": [ ...

The issue with disappearing HTML elements on input focus was resolved in iOS 8.3

I encountered a peculiar issue that bears resemblance to the fixed element problems on iOS highlighted on Stack Overflow, but with a unique twist. This anomaly only occurs when the parent document is scrollable and involves the use of an iframe. Below is a ...

Unable to load variables into site.css in order for Flask app to successfully render home.html

I'm encountering difficulties in getting my site.css file to accept two variables passed in from my app.py using Jinja2 templates, namely {{ variable }}. In app.py, I have defined two variables named empty_fill_line and fill_line, which dynamically up ...

Tips for optimizing the reuse of Yup validation schemas and improving the duplication coverage on sonar scans for Yup validation files

I am currently dealing with multiple forms that have some fields in common such as name, phone number, and account number. I am utilizing Formik and have created a schema file (schema.js) for each form. Within this file, I have outlined all the schema vali ...

Having trouble with Vuetify's 'text-wrap' class not functioning properly for wrapping text to the next line? Find out

I'm encountering an issue where words get cut off on my cards and are moved to a new line. Here is an image showing the problem: https://i.sstatic.net/9mWbx.png I attempted to resolve this issue by using the class="text-wrap", but it did no ...

What is the method for sending parameters to PHP from an HTML file using AJAX?

My protfolio.html file contains a table #gallery with different categories. I want to dynamically update the content of the #gallery based on the selected category using ajax. I have a php file that scans a specific folder for images related to the categor ...

How to properly position a YouTube video frame in the center?

<section> <h3>Find out about us</h3> <p>British Airways Virtual is a leading virtual airline within the Infinite Flight community. Boasting a community of over 50 pilots, we offer a vibrant and engaging experience. Come and ...

Incorporating Ruby on Rails tag within JavaScript

Within my html.erb file, there is an HTML button. This button is responsible for generating HTML controls and appending them to a table. Previously, everything worked smoothly without any Ruby on Rails script involved. However, now I have integrated a sele ...

using an array as a parameter in an axios request

For the request I'm working on using Axios, I'm aiming to send an array like this [1,2,3,4]. This array will be used for a selection query in my backend. My question is whether it's better to use a GET or POST request for this purpose, and w ...

The Javascript code is failing to run following an ajax request

When I use XMLHttpRequest.send to call a php script that contains some javascript code, the javasript in the called php script does not run. The process of making the call: var formdata = new FormData(); formdata.append("uploadfilename", file); var ajax ...

Analyzing file data while uploading the file

Does anyone have a solution for extracting the content from an uploaded file in express/nodejs without saving it as a temporary file? I have code that successfully pipes the input to a filestream, but I'm struggling to deserialize the upload to a pla ...

Eliminating the GWT Window Padding in LibGDX

Explanation: I am currently in the process of deploying a LibGDX GWT application to the browser. Challenge: In the image below, you can see the top left portion of my GWT application showcased by the large black rectangle. The issue here is the unwanted ...

Having difficulty targeting the span element in my CSS code

I've got an HTML document that includes multiple span elements. <span>Skip to content</span> There are several of these span elements throughout the document. I've attempted to hide them using the following CSS: span {display: non ...

What is the most effective approach for addressing errors in both the server and client sides while utilizing nodejs and express?

Seeking the most effective approach for handling errors in a response - request scenario. Here is an example of a route that receives a request: app.get('/getInfo', function (req, res, next) { let obj = {} try { obj = { ...

What is the best way to keep an image fixed at the bottom, but only when it's out of view in the section

There are two buttons (images with anchors) on the page: "Download from Google Play" and "Download from App Store". The request is to have them stick to the bottom, but once the footer is reached they should return to their original position. Here are two ...