Trouble encountered when attempting to update the background image through the .css() function in jQuery

My current approach involves using the .css() jQuery method to modify the background of a div identified as "background". This method requires specifying the property name and the desired value. The code I have written is:

function changeBackground() {
      $("#background").css("background-image", "url(../assets/background2.jpg)");
}

window.onload = function() {
      window.addEventListener("click", changeBackground);
};

The initial value for background-image was set to url(../assets/background.jpg). Interestingly, this setup functions properly in the Chrome session where my editor (Brackets.io) Live Preview operates, but not in a normal Chrome or when using Firefox and Opera.

EDIT: The problem originated from the path: instead of only changing the value temporarily in the css file (which was my initial assumption), it appears that jQuery itself manages the modification in the background source. Consequently, the image path must be defined relative to the javascript file—thus, utilizing url(assets/background2.jpg) rather than url(../assets/background2.jpg). Feel free to provide any corrections if necessary.

However, a new concern emerged—once jQuery alters the source of the background image, the remaining styling details from below are completely overlooked. How would one go about resolving this issue?

#background {
background-image: url(../assets/background.jpg);
background-attachment: fixed;
background-position: center;
background-size: cover;    
position: fixed;
top: 0em;
left: 0em;
height: 100%;
width: 100%;    
margin: 0em;
}

Answer №1

Prefer using single quotes ' instead of double quotes " :

$("#background").css("background-image", 'url(../assets/background2.jpg)');

If the above code doesn't work, you can try these alternatives:

$("#background").css({backgroundImage : 'url(../assets/background2.jpg)'});

or

$("#background").css('background', 'url("../assets/background2.jpg")');

Answer №2

apply a new CSS class called .new-background

// css
.new-background {
    background-image: url(../assets/background2.jpg);
}

also, add the following JavaScript code:

// js
function updateBackground() {
  $("#background").addClass('new-background');
}

$(window).click(updateBackground);

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

Delete the <script> tag prior to running

I am attempting to eliminate additional <script> tags from the body using only pure javascript. The HTML structure of the page in question is as follows: <html> <head> <script type="text/javascript"> var scripts ...

Having trouble understanding why the border-radius attribute is not being applied to tables?

I've been trying to give the outer corners of tables a rounded appearance in HTML/CSS, but I can't seem to get the border-radius property to work properly. After inspecting the elements in Chrome's computed section, I noticed that the eleme ...

Validation with Joi: When the object aligns with the schema, validate it against multiple items

Currently, I have an array of objects that need to be validated against specific schemas. If any object matches with a given schema, I want the validation process to only check against that particular schema and move on to the next item in the array. I at ...

Adding information into a column with axios

I have built my ReactJS app using function components and I am currently trying to display user data from my APIs in a datagrid format. However, when testing my code, I encountered an error in the console stating "TypeError: destroy is not a function". I b ...

What are the issues with this straightforward joining of strings?

Trying to merge multiple lines of text in a file using Node.js but experiencing unexpected results. It seems like the previous line is being overwritten, and I'm not sure why. Merging 'Line' with its subsequent 'Sub' items on th ...

Is there a way to show a fallback message for unsupported video file formats?

When incorporating a video element on my webpage, I typically use the following code: <video src="some source" controls> Error message </video> Based on my knowledge, the "Error message" will only appear if the browser does not support the ...

Initiate automatic submission

After receiving some valuable assistance from users on stackoverflow, I've successfully implemented the following code. However, I've now realized that it needs to be triggered when the page loads instead of on a trigger. Since I am new to client ...

Master the art of horizontal scrolling in React-Chartsjs-2

I recently created a bar chart using react.js and I need to find a way to enable horizontal scrolling on the x-axis as the number of values increases. The chart below displays daily search values inputted by users. With over 100 days worth of data already, ...

Customize form input using Javascript prior to inserting into database

On my Rails form, I have a basic setup like the following: <%= form_for @song do |f| %> <p> <%= f.label :url %><br> <%= f.text_field :url %> </p> <p> <%= f.submit %> </p> <% en ...

What is the best way to apply inline styling to a video/gif embed code that is outside of the document object model (DOM)?

My collection includes a variety of embed codes from different gif/video sites, such as: <iframe src="https://player.vimeo.com/video/122375452?title=0&byline=0&portrait=0" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowf ...

Node.js fails to send a list of all clients

js. I have conducted a series of tests successfully so far. Hello world Server-client communication with events Multiple rooms However, I am facing an issue in sending messages to the clients using socket.io The main reason for this is to maintain a li ...

How to make an angular Factory access its own data

I've been working on a project involving angular factories, and I'm encountering an issue where the factory is not able to reference some of its own data. Specifically, in the code snippet below, data2 should be reading the value from testVariabl ...

JavaScript's getDate() function is failing to properly adjust the date when performing addition and subtraction operations

I have been facing an issue with a JavaScript function that is supposed to adjust the date when a button is clicked. The function is intended to utilize the getDate() function to subtract 7 days from the current date value displayed in the textbox. However ...

error occurred while retrieving XML using jQuery AJAX

I am facing an issue with pulling an RSS feed using jQuery AJAX. Each time I attempt to do so, I encounter a parsererror. Despite my efforts to simplify the XML document returned by stripping it down and trying various combinations, the error persists even ...

Organizing Content with Bootstrap - Utilizing Sections and Divs

Currently utilizing a Bootstrap template for my website development, I am encountering two challenges that have me stumped: 1) Upon placing my HTML code within a <section>, an automatic top margin/padding seems to be applied to the section. Despite ...

Obtaining the name of the image that has been uploaded using jQuery

//Image upload function $(function() { $(":file").change(function() { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = imageIsLoaded; reader.readAsDataURL(this.files[0]); } }); }); function im ...

What is the method for presenting an integer column from a specific table to a user on the front end as a series that automatically increments from 1?

I'm currently developing a comprehensive full-stack application designed to function as a task and project management tool. It features a table layout with a convenient drag and drop functionality that enables upper-management to easily re-prioritize ...

What is the best way to align a div right below an image that has been clicked on?

I am designing a website that features social media icons spread out horizontally across the page. When a user clicks on one of these icons, I envision a pop-up window appearing below it, displaying additional information. Here is a visual representation o ...

Querying Firebase for objects will return a collection of data that

I need assistance with querying a Realtime Database structure for AEDs based on their owner. I want the query to return all AEDs (including children) that have a matching owner id. Despite my efforts, I have been unable to achieve this even though it seem ...

Inconsistent functionality observed with the Check Box and recently added component

Hey there, I'm currently working on building a new component using checkbox data. Here's the code snippet I have: import React from "react"; import BottomScrollListener from "react-bottom-scroll-listener"; import ThingsQuery f ...