Is there a way to set a default CSS background image using JavaScript in case the specified

When working with regular CSS, I can easily set a fallback image using this code in case the primary image is not available:

.container {
  background-image: url(pics/img.webp), url(pics/img.png);
}

But when it comes to setting styles in JavaScript (such as with React), how can one accomplish this?

Any assistance on this matter would be greatly appreciated. Thank you :)

Answer №1

Similar to CSS but with a twist

document.body.style.backgroundImage = "url('pics/img.webp'), url('http://placekitten.com/200/300')";

When styling an element in react, here's a simple approach

style={{  
  backgroundImage: `${bgImagePath}, ${bgFallbackPath}`,
  backgroundPosition: 'center',
  backgroundSize: 'cover',
  backgroundRepeat: 'no-repeat'
}}

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

Troubleshooting the "Uncaught Error: 't' is read-only" issue in MUI DataGridPro

My attempt to utilize MUI DataGridPro is encountering an issue where instead of rendering my data, I receive an "An error occurred" message. The data is hardcoded into the component, so its absence is not the problem. The console displays the following er ...

Putting AngularJS controller through its paces using Jasmine

Here is the code for my NewPageCtrl.js file: angular.module('NewPageCtrl', []).controller('NewPageController', function($scope, $document) { $scope.showMe = false; }); And here is the content of test.js: describe('NewPageC ...

Utilizing JavaScript to present JSON data in HTML tables across various sections of a website

Utilizing JScript to retrieve data from a JSON API URL, I have incorporated the data in the JSON file displayed below - containing information on 8 horse races with details like Horse number, Horse name, and their odds. My goal is to create a Jscript code ...

"Utilizing Javascript in an ERB view file within the Rails framework

In my .js.erb file, I need to execute a conditional statement when an ajax call is triggered. Below is the code snippet: function updateContent() { $('.organiser__holder').html('<%= escape_javascript render("filter_links") %>' ...

Transferring radio button selections from a form to Google Analytics upon submission

I have a form where I can capture user selections from radio buttons and a drop-down element using the .blur() event. However, I am struggling with pushing this data to Google Analytics (GA) when the user clicks the submit button. Currently, my script loo ...

Error message: JavaScript JSON variable undefined in AWS Lambda

My lambda function is being triggered by an IoT rule that sends a MQTT message in JSON format. I am facing an issue where the top level fields are logging correctly, but when it comes to nested objects in the JSON, they appear as "undefined". Even after tr ...

The mysterious nature of React's setState function

Situation 1 increaseScoreBy3 () { this.setState({score : this.state.score + 1}); this.setState({score : this.state.score + 1}); this.setState({score : this.state.score + 1}); } Situation 2 increaseScoreBy3 () { this.setState({score ...

table with flexible cell width and fixed table width

I've been troubleshooting this issue for days, but I just can't seem to find a solution! The problem lies within a table used on a webpage. If I don't specify table-layout, I can make one cell width dynamic, but I lose the ability to set &a ...

When using the `sendFile` method in Node.js Express, you will notice that the HTML content

Hey there, I'm new to nodejs and trying to create a simple website with two pages. I'm facing an issue where the content of the second file is being rendered as the first one, even though the source inspector in the browser indicates that it&apos ...

Hide bootstrap card on smaller screens such as sm and md

Utilizing the Bootstrap 4.1 card component, I showcase categories within the right sidebar - check out a sample image of the card here: Card example image; When viewing on smaller screens, it's preferable to collapse this large card as shown in this ...

Develop an AJAX script for processing multiple form inputs in PHP and HTML

I am working on a code that involves multiple form submissions, but the submit functionality is not working due to having multiple submits on one page. I have realized that I need an Ajax script to handle this, but I am new to it. Can someone provide me wi ...

Transform JSON into a JavaScript array object using node.js

My knowledge of Javascript is limited and I need assistance with a .json file that has the following structure: { "results": [ { "challenger": { "__type": "Pointer", "className": "Player", "objectId": "STWAxAHKay" }, "c ...

Change the color of the Material UI InputLabel

Seeking assistance with my input label: <InputLabel>NAME</InputLabel> The text is currently displaying in white, which makes it difficult to read against the white background. Can someone provide guidance on how I can change the color to blac ...

The getElementBy method is failing to pass the value in the document

Here is the javascript code snippet I am using: document.getElementById('district').value = dist.long_name "this line is passing the value" document.getElementById('city').value = route.long_name "this doesn&apos ...

Preventing runtime error in Next.js API routes by handling axios exceptions

I am currently working on creating an API route in Next.js that sends a request to my backend and saves the token in the cookies. However, I am facing an issue where 4xx responses are causing an Unhandled runtime error. Despite everything working correctly ...

struggling with utilizing ajax for outputting data using PHP and POST variables

Currently, I am attempting to execute a PHP script that retrieves data from a database by simply clicking a button. My intention is to implement AJAX in order to prevent the page from refreshing. While testing with traditional post/submit methods and enc ...

Screen readers are unable to "read" text that is identified through aria-describedby

When enhancing my web application for accessibility, I encountered a challenge. I have implemented two required fields in a form that should display separate error messages as spans. To accomplish this, I am utilizing aria-invalid to signal when the fields ...

Combine es6 imports from the identical module using an Eslint rule or plugin

Looking to consolidate my ES6 imports from a single module into one for my React project. For example: import { Title } from "@mantine/core"; import { Center } from "@mantine/core"; import { Divider } from "@mantine/core"; T ...

Validation of Button Groups and Automatic Disabling after Initial Click with HTML, CSS, and JavaScript

Criteria: Upon clicking a button from the selection of four buttons, all other buttons should become disabled except for the Next button. An alert window must appear when the Next button is clicked without selecting any other buttons, preventing navigatio ...

Identifying when an image element is within the viewport using jQuery Mobile

Looking for a solution to bypass the image size download limit on mobile devices by detecting when an image is in view and then downloading it. Also interested in replacing the image src with a smaller image to free up memory. Any tips on how to efficientl ...