What is the process for setting a background image using two alternate images? (ensure a substitute image displays when the original image is not available

I am trying to set a background image with two alternatives. Below is the code I have been using:

<a id="test" style="background: url('image1.png'), background: url('image2.png');">test</a>

My goal is to prioritize the first image (image1.png) and if it does not exist, then set the second image (image2.png). However, currently, when both images exist, both are being set on the a tag...

I would like to only set the first image if it exists, and only set the second image if the first one is missing.

Can someone please advise me on how to solve this issue?

If there is no direct solution, is there a way to handle this through a jQuery event? I attempted to catch an error using the following code, but was unsuccessful:

$("[id='test']").error(function() {
    alert( "Handler for .error() called." )
});

Answer №1

background Capable of setting multiple backgrounds simultaneously.

background:url("bg1.jpg") 0 0 no-repeat,
           url("bg2.jpg") 200px 0 no-repeat

The top layer is bg1 and underneath is bg2. If bg1 image doesn't exist, it remains hidden. bg2 is automatically displayed.

Feel free to experiment by swapping out the image links below:

.bg-wrap {
    width: 100px;
    height: 100px;  /* Play around with deleting the bg1 background URL */
    background: url("https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=248222817,375547763&fm=26&gp=0.jpg") 0 0 no-repeat,
                url("https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2901784552,1261367458&fm=26&gp=0.jpg") 0 0 no-repeat
}
<div class="bg-wrap"></div>

Answer №2

To achieve the desired effect, you can use a pseudo element "before" and set its dimensions to match those of its parent element. Check out the code snippet I provided below. I'm not entirely sure if this is what you're looking for, but hopefully, it points you in the right direction.

#test {
  color: green;
  background: url(https://dummyimagee.com/100x100/000/fff); /* incorrect path */
  /* background: url(https://dummyimage.com/100x100/000/fff); */ /* correct path */
  width: 100px;
  height: 100px;
  display: inline-block;
  position: relative;
}

#test::before {
  content: '';
  display: block;
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: url(https://dummyimage.com/100x100/ff0000/0011ff);
  z-index: -1;
}
<a id="test">test</a>

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

How to ensure an element is always aligned at the end of a line in ReactJS, no matter the screen dimensions

I have a unique element that rotates words at a set interval. <div className="inline-block flex justify-center items-center before:content-['lore_ipsum_dolor_lore_ipsum_dolor'] drop-shadow-[0_3px_3px_rgba(0,0,0,1)] t ...

The table row disappears but the value persists

I have designed a table where users can perform calculations. However, when a row is deleted, the values from that row appear in the row below it and subsequent rows as well. What I want is for the user to be able to completely remove a row with its values ...

"Experimenting with KinectJS: Adding Rotation to a Pair of Images

Looking for a solution to rotate both the upper arm and forearm images simultaneously? The upper arm rotates around a specific point, and the forearm also rotates around this same point. How can I make sure that the forearm rotates when the upper arm does ...

Your browser's popup blocker is preventing the file from being downloaded

I am encountering an issue with my PHP file download function where the browser's popup blocker is preventing the file from opening. My objective is to create an HTML form submit button that will send a form, modify an RTF file on the server based on ...

Position the final list item in the column on the left side

Currently, I am facing an issue with creating spacing between li elements in a column layout. The problem arises when the last li in the column does not align to the far left edge of the column width. Take a look at the screenshot below for reference: Bel ...

Varied approaches to managing responsive layouts

I am encountering an issue with the responsive design of a website I am currently developing. Scenario: The website features 3 different layouts for Desktop, Tablet, and mobile devices. These layouts consist of similar components with slight CSS adjustmen ...

How do you transfer drop-down values from an HTML template to views in Django?

I am trying to figure out how to pass the selected option value in a drop down menu to the views. The HTML code of my template is as follows: <select name="version" id="version" onchange="location = this.value;"> &l ...

Troubleshooting Bootstrap: Issues persist even after including CDN links and reference style link // Python

Currently, I'm in the process of constructing my Django app. After successfully implementing the login page and homepage, I decided to give my page a much-needed facelift since it looked extremely basic. A big fan of Bootstrap, I've used it exten ...

Having trouble with applying a class in Gtk3 css?

MY ATTEMPT AND EXPLANATION: In my application, I have the following layout structure: GtkWindow GtkOverlay GtkBox GtkGrid GtkButton Even after trying to apply this CSS style: GtkButton{ background-color:blue; } T ...

What is the best way to generate a personalized error message when an HTML5 required input pattern fails to meet the criteria?

I am facing an issue with the following code snippet: <input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" /> After entering just one character, I receive a message that says: " ...

Images that have been resized on Android appear blurry when viewed on the second page

Customizing the Toolbar: #main_bar { background: url(../images/logo.jpg) 99% 50% no-repeat; background-size: auto 80%; } The original size of logo.jpg is 220x266px The toolbar has a fixed height of 46px Therefore, the background image appears t ...

Vue.JS and its Onclick event handler allows for dynamic and interactive

These are my two buttons: <button onclick="filterSelection('Action')">Action</button> and <button onclick="filterSelection('Adventure')">Adventure</button> Now, I'm trying to achieve the same fun ...

Permitting various valid responses for questions in a multiple-choice test | Utilizing Angular.js and JSON

As a beginner in this realm, I must apologize if my query seems naive. I recently crafted a multiple-choice quiz using HTML, CSS, JavaScript (angular.js), and a JSON data file following a tutorial I stumbled upon. The outcome pleased me, but now I am face ...

Altering the color of a Fabulous Icon in real-time

I'm having trouble changing the color of an Awesome Icon with this code I created. Instead of getting the desired color, I am getting 'undefined' as a result. <script type="text/javascript"> function changeAIColor(idName) { alert ...

Conceal certain elements from being printed by the client side on a website

Imagine logging into social media but not wanting to see the number of "likes" on posts as the page loads. For example, when you open a photo from a friend and underneath it shows "Somefriend, someotherfriend, and 123123 persons like this", you may want t ...

Applying ngClass to a row in an Angular material table

Is there a way I can utilize the select-option in an Angular select element to alter the css-class of a specific row within an Angular Material table? I have successfully implemented my selection functionality, where I am able to mark a planet as "selecte ...

Hovering over a link within a paragraph will not trigger the :hover effect

I attempted to apply the :hover effect specifically to a link inside a paragraph. The paragraph with the class .hop is initially hidden, but when I hover over the link, nothing happens. .hop { display: none; } a.hop2:hover + .hop { display: block; } ...

Generate a smooth, flicker-free card flip animation in CSS3 across all browsers while addressing any z-index or perspective issues

Currently, I am attempting to implement a simple cross-browser 3D CSS3 card flip effect on my testing website. The outcome functions perfectly in Firefox; however, in WebKit, one part of the image vanishes during the rotation and also experiences noticeab ...

Having trouble with JavaScript in a project I'm trying to replicate

For my coding practice, I am working on a project where clicking on the images should change the main product displayed along with its color. However, nothing happens when I click on the products. Can anyone point out what I might be doing wrong? Here is ...

What is the best way to open an already existing tab in Safari using an HTML 'a' link?

Is it possible to return to Safari after launching another app? <a href="webbrowserapp://example.com/open?url=http.....">Open WebBrowserApp</a> I've tried using: <a href="safari://">Return to Safari</a> It would be ideal if ...