Looking to replace a background image using javascript?

(apologies for any language mistakes)

I have multiple divs with a common background image. I assigned them the same class and set the background image using CSS in style.css which worked perfectly fine. Now, I want to change the background image dynamically by adding an onclick function to the divs. This function is supposed to replace the old background image with the new one.

I've experimented with different approaches:

Initially, I tried resetting the URL in the onclick function like this:

chal = document.getElementById('chal' + x + n);
chal.style.backgroundImage = "url('../../../images/backgrounds/challenge_unknown_gold.png')";

Although I expected it to update the background image, the old image persisted.

Next, I removed the initial background to test if changing the order works, and indeed it did. When no background was set previously, the new image displayed correctly.

Realizing that the new background image would load, I attempted setting the initial background via JavaScript and removing it through CSS:

document.getElementsByClassName("")[0].style.backgroundImage = "url(''); 

This approach also worked, but clicking on the div didn't trigger any action.

Then I attempted clearing the initial background before setting the new one:

 chal.style.backgroundImage = "";
  chal.style.removeProperty("background-image");
  chal.style.background = "none";

Despite these efforts, the issue remained unsolved, and now I could see the edges of the new background image beneath the old one.

I'm unsure how to resolve this without complicating the code unnecessarily. One solution might involve duplicating each div to include the new background and using display: none. However, I am hopeful that someone can suggest a smarter alternative.

Thank you!

Here is the provided Code:

HTML:

<!DOCTYPE html>
<html lang="de">
<head>
    [...]
    <link rel="stylesheet" href="snake_style.css">
</head>
<body>
  <main>
    <div>
       <div id="chalA1" class="challenges bronze" onclick="giveXP('A', 1)"></div>
       <div id="chalA2" class="challenges bronze" onclick="giveXP('A', 2)"></div>
       [...]
       <div id="chalB1" class="challenges bronze" onclick="giveXP('B', 1)"></div>
       <div id="chalB2" class="challenges bronze" onclick="giveXP('B', 2)"></div>
       [...]
    </div>
    <script type="text/javascript" src="snake_script.js"></script>
  </main>
</body>

CSS:

.challenges {
    background-repeat:no-repeat;
    background-position: center center;
    background-size: contain;
    display:flex;
    justify-content: center;
    align-content: center;
    margin: 0.25rem;
    padding:0;
    border: none;
}
.bronze{
    background-image: url(../../../images/backgrounds/challenge_unknown_bronze.png);
}
.silver {
    background-image: url(../../../images/backgrounds/challenge_unknown_silver.png);
}
.gold {
    background-image: url(../../../images/backgrounds/challenge_unknown_gold.png);
}

Javascript:

let chal;

function giveXP(x, n) {
[...]
     chal = document.getElementById('chal' + x + n);
     chal.style.backgroundImage = "";
     chal.style.backgroundImage = "url('../../../images/backgrounds/challenge_unknown_gold.png')";
[...]
                     
}

Answer №1

When updating the background image with JavaScript, avoid using quotes around the path

Issue with quotes:

https://i.sstatic.net/1Sc0M.png

Replace this:

chal.style.backgroundImage = "url('../../../images/backgrounds/challenge_unknown_gold.png')";

With this:

chal.style.backgroundImage = "url(../../../images/backgrounds/challenge_unknown_gold.png)";

Here is an example for reference:

const bgImage = document.querySelector('.bg-image');
        const changeBgBtn = document.querySelector('.change-bg-btn');

        changeBgBtn.addEventListener('click', () => {
            bgImage.style.backgroundImage = `url(https://cdn.pixabay.com/photo/2016/11/19/15/32/laptop-1839876_1280.jpg)`;
            bgImage.style.backgroundPosition = 'left center';
        })
* {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        .bg-image {
            width: 100%;
            height: 100vh;
            background-image: url("https://cdn.pixabay.com/photo/2016/11/23/14/45/coding-1853305_1280.jpg");
            background-position: top right;
            background-size: cover;

            display: flex;
            justify-content: center;
            align-items: center;
        }

        .change-bg-btn {
            padding: 14px 20px;
            border: none;
            outline: none;
            border-radius: 5px;
            background-color: #fff;
            cursor: pointer;
            font-size: 1.2rem;
        }
<div class="bg-image">
      <button class="change-bg-btn">Change Background</button>
</div>

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

One beneficial aspect of utilizing JavaScript closures for events is when defining a click event

There are two common ways to write code in JavaScript that accomplish the same task: Option A. SomeObject.prototype.hideElement = function(e, element){ e.stopPropagation(); hide(element); } Option B. SomeObject.prototype.hideElement = function( ...

A tutorial on creating circular patterns within a pyramid structure using p5.js and matter.js

I've been attempting to create a pyramid shape using multiple circles, similar to this: balls in pyramid shape To achieve this, I've developed a 'Balls' class: class Balls { constructor(x, y, radius, color, ballCount) { this.x = ...

How can JavaScript onClick function receive both the name and value?

My current challenge involves a function designed to disable a group of checkboxes if they are not checked. Originally, this function was set to work onClick(), with one argument being passed from the checkbox element. Now, I need this function to be trigg ...

Verify if there are DOM elements located within a DIV container, execute the functions associated with those elements sequentially

I am in the process of creating a game using HTML, CSS, and JavaScript. My focus right now is on manipulating DOM elements without relying on the canvas tag. The goal is to develop a pseudo graphical programming language, similar to the environment provide ...

The presence of multiple renderings occurring due to Google Maps InfoBox and an AJAX call

I'm encountering a problem with my implementation of the InfoBox and I'm looking for insights on potential solutions. Currently, I have around 1000 client-side markers that are dynamically added to the page. They are created using the following ...

Retrieving data from a remote PHP server using JavaScript

I am currently working on two separate websites. Site A is coded using only HTML and JavaScript, while site B utilizes PHP. I am trying to figure out a way to access variables from site B within site A. For example: The code for site A looks something li ...

AngularJS checkbox validation requires a minimum of two checkboxes to be selected

When using AngularJS, I am looking to create a validation rule where a minimum of 2 checkboxes must be checked for the input to be considered valid. Here is what I have attempted: <div ng-repeat="item in items"> <label><input type="chec ...

What could be causing the second switchMap to be triggered repeatedly upon subscription?

Check out the code snippet below for reproducing the issue: import { defer, BehaviorSubject, of } from "rxjs"; import { shareReplay, switchMap } from "rxjs/operators"; const oneRandomNumber = defer(() => of(Math.floor(Math.random() ...

How can you identify the specific HTML page that a jQuery selector is targeting?

In an attempt to create jQuery code that counts the number of <img> elements on a website, I encountered a unique challenge. The website consists of 4 separate HTML pages stored in the same folder on the server. Among these pages, only "pics.html" is ...

What is the reason I am unable to upload personalized templates using <script> elements?

I have a dilemma where I need to swap out multiple templates from a library with my own custom ones without forking the original templates. When I include the templates in my index.html page like: <script type="text/ng-template" id="first-template"> ...

Troubleshoot mobile overflow-x problem when expanding div beyond container boundaries

Recently, I experimented with a method to extend the background-color of my div outside its container. Everything was working fine except for the fact that applying overflow-x to the body on mobile browsers didn't completely disable horizontal scrolli ...

The Javascript eval method throws a ReferenceError when the variable is not defined

In my constructor, I was trying to create a dynamic variable from a string. Everything was working smoothly until I suddenly encountered this error out of nowhere. I didn't make any changes that could potentially disrupt the system, and the variables ...

Tips on linking a condition-reaction to document.querySelector

I am struggling to connect the condition-reactions to the input id of passid. I am unsure where to place the document.querySelector() method in order to link the indexed conditions correctly. Below is the code snippet: <!doctype html> <html> ...

Using a render target causes certain elements of my visual graphics to become hidden

Hey there, I've been experimenting with render targets lately and encountered some issues. I've put together a simplified example below: init = function() { // RENDERER canvas = document.getElementById("mycanvas"); renderer = new THREE ...

serving static content on subdomains with Express JS

I created an API using Node.js Express JS and utilized apidocjs.com to generate the static content. The issue I am currently facing is that I want the documentation file to be located under a subdomain such as docs.example.com or api.example.com/docs. What ...

Showing off HTML tags within react-json-tree

I have incorporated the following npm package into my project: https://www.npmjs.com/package/react-json-tree My goal is to showcase a json tree in react, but I am facing a challenge on how to include an HTML tag as a JSON value. Are there any alternative ...

Angular: Exploring the possibilities of condition-based click event implementation

In my component, there are two elements: 'order information' and a 'datepicker'. When clicking on the component, it will display the order information. However, I want to prevent the click event from being triggered if the user clicks ...

When using AutoComplete in MUI, I encountered an issue while attempting to assign a default value to the checkbox from an API. Instead of achieving the desired result, I received an error stating "(inter

Within this snippet, I am seeking to retrieve a default value from the API to populate a checkbox initially. I have employed the Material-UI Autocomplete component, which includes a defaultValue prop. Despite my efforts to utilize this prop, I am encounter ...

What is the best way to cycle through a nested JS object?

I am currently utilizing useState and axios to make an API call, retrieve the response, and pass it to a Component for rendering. const [state,setState] = useState([]); const getCurrData = () => { axios.get('working api endpoint url').then(r ...

Exploring the Collapse and Dropdown features in Bootstrap 5 Navbar

Struggling with my navbar on Bootstrap 5 - the collapse feature isn't working after expanding, and the dropdown list fails to drop down. <!-- Using Bootstrap-5 --> <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-pro ...