Transfer the background-image from one div to another

I have several div elements that act as buttons, each with a different background image set in the CSS file:

#button1 { background-image: url('../images/abc.png) }
#button2 { background-image: url('../images/def.png) }
#button3 { background-image: url('../images/ghi.png) }

Every button belongs to the class "button".

Additionally, there is a div with the class "popup". When any button is clicked, the class "isActive" is added.

My goal is to extract the background image of the button with the "isActive" class and apply it to the "popup" div.

I attempted to achieve this using jQuery:

var bg;
bg = $('.isActive').css('background-image')
console.log(bg)
$('.popup').css('background-image', bg )

However, the console.log returns the full path, such as:

file:///C:/Users/me/projects/images/abc.png

Is there a more elegant way to retrieve only the relative path without including "file://" and so on, just "../images/abc.png" as specified in the CSS?

Answer №1

To add different backgrounds to your popups, simply create CSS classes for each background image and then apply them as needed.

.bgr1 { background-image: url('../images/abc.png) }
.bgr2 { background-image: url('../images/def.png) }
.bgr3 { background-image: url('../images/ghi.png) }

Next, use the following code snippet to assign the appropriate background:

var allClasses = ['bgr1', 'bgr2', 'bgr3'];
var bgr = $('.isActive').attr('class').split(' ').filter(cls=>allClasses.indexOf(cls) > -1).shift();
if (bgr)
    $('.popup').addClass(ngr);

Update

This code snippet was taken from a thread on Stack Overflow: Copy background from one element to another using jQuery not working in firefox:

$('.popup').css('background', $('.isActive').css('background-image'));

Answer №2

If you are looking for an answer, check out this resource: Get BackgroundImage

$(this).css('background-image');

Answer №3

Remember: The source of your JavaScript code should be specified relative to your HTML or PHP file, not your JavaScript file.

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

Is there a way to apply border-radius to the header of a table in Bootstrap 5?

My use of Bootstrap 5 for styling a table has encountered an issue. Even with the border-radius set on the table-dark class, the thead element's border does not change. I am looking for a way to address this problem. Any suggestions? .table-dark { ...

Unexpected Placement of CSS Grid Items

I am currently facing an issue with aligning items in a nested grid using grid-column/grid-row assignment. After setting the template with grid-template-rows:/grid-template-columns, I expected the $50 and Give Now items to appear on row 3, with one in colu ...

Looking to obtain rendered tree data upon page load?

Is there a way to retrieve all rendered tree metadata when the page loads using jstree? I'm looking for an output similar to this: [23,24] Please note that I would like to have each id stored in the metadata object displayed as [23,24] upon page loa ...

When information is provided, record the values in a separate input field

I'm struggling to come up with an appropriate title... Here's the issue: if a user inputs anything into the "Accompanying Person" field, the "Accompanying Person Price" field will automatically be set to 260€. I have no clue on how to achieve ...

Fade in effect with jQuery causing a flashing issue specifically in Firefox

I am facing a problem with an overlay and modal window popping up on the screen. Whenever I use the code below, there is a flash in Firefox before the overlay and modal window fade in. How can I eliminate this flash? I want to ensure that the fadeout is co ...

Is there a way to automatically refresh the woocommerce checkout page every 20 seconds?

I'm currently facing an issue with my woocommerce website. The dilemma I'm encountering is the need to automatically refresh the checkout page every 20 seconds upon clicking the place order button. This requirement stems from a plugin that prov ...

ajax id must be defined and not undefined

I have some code that is not working properly. In barang.php, the following code is present: barang.php <?php $p=isset($_GET['act'])?$_GET['act']:null; switch($p) { default : echo '': break; case " ...

Display a DIV element when hovering over another DIV element using CSS or JavaScript without them being directly related as parent and

So I've figured out how to use CSS to show a hidden div when you hover over its parent. But what if the hidden div is not a child of the parent you want to hover on? How do you make it appear then? For example: <div class="field-1"></div> ...

jQuery failing to recognize clicks on dynamically added element

Here's the scenario: <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header" ...

Is there a way for me to choose multiple checkboxes simultaneously?

I have a dynamically created HTML table with checkboxes added for each row. $.each(data, function(id, value) { rows.push('<tr><td><input type="checkbox" autocomplete="off" class="chkbox" name="chkbox" value="'+value.site+' ...

What is the best way to resize an image to match the height of its flex item sibling?

After reading this answer, I attempted to adjust the size of a flex-item img element to match the height of its sibling. The height was adjusted correctly and the image shrunk accordingly while maintaining its aspect ratio, but the img element still took u ...

Add an event listener to a dynamically created div block through jQuery when it is clicked

When the page loads, a dynamic div appears that is visible to the user and in Firebug, but is not available in the page source. The content within this div changes dynamically. I am attempting to bind a click event to this div so that when a user clicks o ...

How can I change the background color as the page is scrolled without using jQuery?

Does anyone know how to create a transition effect with CSS where the background color fades into another color based on the position of the page, similar to the effect triggered by divs with the same class? I came across a JavaScript solution that works p ...

What is the best method for choosing the parent elements?

I am attempting to create a sidebar that saves the last clicked link in local storage and still displays the collapsed links after the page is reloaded. $(".clickedLink").parent().parent().css('background-color', 'green'); Ca ...

What sets apart :first-child from :first-of-type?

I need help understanding the distinction between element:first-child and element:first-of-type Let's consider a scenario where you have a div element div:first-child → Refers to all <div> elements that are the first child of their parent. ...

Setting the width of a div element dynamically according to its height

Here is a snippet of my HTML code: <div class="persoonal"> <div class="left"></div> <div class="rigth"></div> </div> This is the CSS code I have written: .profile { width: 100%;} .left { width: 50%; float: le ...

"Customizing the gaps between cluster bars on AmCharts JS for a clean and professional

Previously, I utilized the AmCharts flash version where creating clustered column/bar charts like the image below was a breeze. In that setup, the clustered bars were tightly packed with no spacing in between. However, transitioning to the JS version of Am ...

Make sure to place the <i> tag within the <li> tag at the bottom to automatically resize the height

Currently, I am working on customizing my menu design with a mix of bootstrap and font awesome CSS styles. It would be easier to demonstrate the issue on a live page. My main objectives are two-fold: I want to position the chevron icon at the bottom with ...

Footer positioned correctly with relative DIV

I find myself in a state of complete confusion. Coding is not exactly my forte, so I suspect I have made a significant error somewhere that is causing the following issue: My goal is to create a sticky footer. The footer does indeed stick to the bottom of ...

Identify Pressed Shift Key Direction - Leveraging JQuery

I am currently working on a web application that requires users to enter capital letters. However, I want to restrict them from using the right shift key for certain keys like a, s, d, f and the left shift key for h, j, k, l in order to detect whether they ...