1

In CSS, I have e.g. the following:

background-image: url("IMAGE_URL"); /* fallback */
background-image: url("IMAGE_URL"), linear-gradient(#eb01a5, #d13531); /* W3C */

I want to achieve the same effect in JavaScript. I.e. I want to set the backgroundImage property, but I also want to set a fallback. But element.style.backgroundImage does not accept a string array.

element.style.backgroundImage = 'url("IMAGE_URL"), linear-gradient(#eb01a5, #d13531)'; // How to include the fallback here?

I don't want to use hacks to check which browser the user is using. If it's not possible, I would also like to know.

2
  • 1
    Could you explain why you need to set it in JavaScript? Is adding or removing a class an option? Are you targeting old browsers? Commented Feb 5, 2021 at 9:50
  • 1
    Inline css does not support inline fallback. Try adding class to element and then write CSS with JS, or simply have pre-written CSS Commented Feb 5, 2021 at 9:51

2 Answers 2

1

Just append a <style> element using JavaScript, and insert the CSS you would have used that way:

document.head.innerHTML += `
<style>
    element {
        background-image: url("IMAGE_URL"); /* fallback */
        background-image: url("IMAGE_URL"), linear-gradient(#eb01a5, #d13531); /* W3C */
    }
</style>
`
Sign up to request clarification or add additional context in comments.

Comments

0

You can probably use CSS.supports and find the first item in an array of values that returns true. Then apply that to style.

Note: not all properties can be detected - notably whether flex gap is supported. Flex box gap is recent but grid gap has been there a while so testing for ‘gap’ is ambiguous.

https://developer.mozilla.org/en-US/docs/Web/API/CSS/supports

This is effectively what the browser is doing when you provide a list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.