Utilize jQuery to duplicate the image source and set it as the background for a div element

I'm struggling with cloning the URL string from the src attribute of an image. My goal is to store the string as a variable so that I can use it to update the background-image CSS property. ... Taking an image and setting it as a background in another element.

I've attempted this within a $(window).load event, as I believe the image needs to be fully loaded before its URL can be accessed in the DOM. However, I've hit a roadblock. I can successfully alert(imgURL); but I cannot get it to apply to the background of the target element.

Below is my current attempt. Any assistance would be much appreciated. Thank you!

$(window).load(function() {
  var imgURL = $('.thumbnail img').each(function() {
    $(this).attr('src');
  });
  $('.fullsize').each(function() {
    $(this).css('background-image', 'url(' + imgURL + ')');
  });

});
.fullsize {
  width: 200px;
  height: 200px;
}
.thumbnail img {
  width: 75px;
  height: 75px;
  float: left;
  cursor: pointer;
}
<div>
  <div class="fullsize"></div>
  <div class="thumbnail">
    <img src="http://twiki.org/p/pub/Plugins/GnuPlotPlugin/BlueWhaleSample.png" />
  </div>
</div>

<div>
  <div class="fullsize"></div>
  <div class="thumbnail">
    <img src="http://twiki.org/p/pub/Plugins/GnuPlotPlugin/RosenbrockFunctionSample.png" />
  </div>
</div>

Answer №1

To ensure the DOM is ready and iterate through all elements with the class .fullsize to find the image inside the thumbnail and replace the background, it's recommended to use $(document).ready(function()... instead of $(window).load(. The script below shows how this can be implemented:

$(document).ready(function() {
  $('.fullsize').each(function() {
    var imgURL = $(this).next('.thumbnail').find('img').attr('src');
    $(this).css('background-image', 'url(' + imgURL + ')');
  });
});

Check out the JSFiddle Demo for reference

Answer №2

Within your code snippet, the variable imgURL is used to reference a jQuery object that contains all the .thumbnail img elements.

Alternatively, you can utilize the .css() method as demonstrated below to locate the src attribute of the img element in the subsequent sibling of the current fullsize element.

$(window).load(function() {
  $('.fullsize').css('background-image', function() {
    return 'url(' + $(this).next().find('img').attr('src') + ')'
  });

});
.fullsize {
  width: 200px;
  height: 200px;
}
.thumbnail img {
  width: 75px;
  height: 75px;
  float: left;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
  <div class="fullsize"></div>
  <div class="thumbnail">
    <img src="http://twiki.org/p/pub/Plugins/GnuPlotPlugin/BlueWhaleSample.png" />
  </div>
</div>

<div>
  <div class="fullsize"></div>
  <div class="thumbnail">
    <img src="http://twiki.org/p/pub/Plugins/GnuPlotPlugin/RosenbrockFunctionSample.png" />
  </div>
</div>

Answer №3

Initially, it is recommended to enclose each div with a specific classname as demonstrated below:

<div class="mainParent">
  <div class="fullsize"></div>
  <div class="thumbnail">
    <img src="http://twiki.org/p/pub/Plugins/GnuPlotPlugin/BlueWhaleSample.png" />
  </div>
</div>

<div class="mainParent">
  <div class="fullsize"></div>
  <div class="thumbnail">
    <img src="http://twiki.org/p/pub/Plugins/GnuPlotPlugin/RosenbrockFunctionSample.png" />
  </div>
</div>

Following that, the best practice would be to execute this on document.ready event in the manner shown below:

$(document).ready(function() {
  $.each('.mainParent',function(){
       $(this).find('.fullsize').css('background-image',$(this).find('img').attr('src'));
  });
});

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

Ways to trigger a server function in JavaScript upon closing a browser tab or the entire browser

How can I trigger a server function when closing a browser tab or window using JavaScript? Similar to this image //Below is the code for my server-side function: public ActionResult DeleteNotPostedImage(string folder , string PostID) { folder ...

Ways to eliminate additional whitespace in CSS Grid styling techniques

Currently, I am utilizing material ui to establish a grid system for showcasing videos in 2 rows. While I have successfully set up the general layout, I am facing difficulty in eliminating the white space/padding between the elements. Despite trying nowrap ...

Count up with HTML like a progressive jackpot's increasing value

I am interested in developing a progressive jackpot feature similar to the sample image provided. I would like the numbers to loop periodically. Can anyone advise me on how to achieve this effect? Any suggestions or examples, preferably using JavaScript o ...

What is the best way to spin a paragraph in Bootstrap?

I've been attempting to rotate this div by 90 degrees, but for some reason, it refuses to cooperate. I've tried using various bootstrap classes with no success, and even plain CSS doesn't seem to have any effect on it. #socials { transf ...

The panel header is clickable and overlaps with the header buttons

My panel component includes a header with a title and buttons positioned in the right corner. Currently, the downward arrow (chevron) is used to toggle the expansion/minimization of the panel's contents. When I attempt to make the header clickable to ...

Transforming CSV CSS values with jQuery's CSS method: Step-by-step guide

My goal is to stack multiple background images within a single div container while ensuring their position is relative to the screen height. The problem I'm encountering is my inability to modify CSS values separated by commas. Here is my logical appr ...

Calculate the total width of LI elements and apply it to the parent UL or DIV

Is there a way to calculate the Total LI width and then set the width for the parent div? Here is an example of my code: <ul> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds</li> <li>dsfdsfdsfds&l ...

Having trouble transferring data from JavaScript to PHP via POST method

Hi there, this is my first time posting and I could really use some assistance. I have a bit of a roadblock with two Symfony forms on a page that don't seem to be working properly. The first form is for a contract, while the second one is used to pop ...

In JavaScript, alert a message once all images have been clicked

I'm encountering a small issue with my javascript code. I am developing a game for a school project where the objective is to click (remove) fish using a fishing rod. However, the game does not have an end condition set up, so players cannot win. Belo ...

Site with Three Steady Columns

While I know that this question has been asked in the past, I'm eager to see if there have been any recent changes. I am currently searching for a fixed 3 column layout using html/css, with the main content (middle) area being located first in the DO ...

Puzzle involving unusual interactions with HTML, JS, and CSS scrollbars

I'm embarking on a special mission using CSS, HTML, and jQuery. My goal is to prevent scrolling when I hover over a specific element on the page. Right now, I'm accomplishing this by setting the body's overflow property to "hidden." However, ...

Tips for avoiding the security risk of "A potentially hazardous Request.Form" in requests

After integrating a FreeTextBox control into my webpage, users can input HTML tags. However, upon submitting to the server, I encounter the following error: A potentially dangerous Request.Form value was detected from the client (GestisciPagine1_txtTest ...

What is the best method for using XMLhttpRequest in PHP to append options to a select element?

I'm looking to dynamically fetch values from a MySQL database using PHP and then add them as choices within a select element. Here is my HTML code: <label for='listDivision'>Division</label><select id='listDivision&apos ...

Requesting data asynchronously using AJAX and displaying the filtered results on a webpage using JSON

When I send a request to my node.js server for a .json file containing person information (first name, last name), I want the data to be filtered based on user input. For example: When I request the .json file from the server, it gives me a list of people ...

Utilizing nested flexboxes to create a horizontal row within a vertical column

As I work on creating a mock survey form, I've organized the input fields in a column flex-box layout. However, I'm facing an issue with the name field where I want to split it between 'first' and 'last' names while sharing th ...

AJAX delivers results by returning HTML code

Despite attempting various solutions from multiple sources, including this one, I still can't pinpoint the exact issue in my code. Here is a snippet of my code: $(document).ready(function() { $("#botname").blur(function() { $.ajax({ ...

Google Maps API - Custom Label for Map Markers

I am trying to implement a custom map on my website, and everything seems to be working fine except for one issue. The red marker on the map needs to have a label, but I don't want to use an additional image as an icon. Is there a way to add a label ...

jQuery fails to display the response upon submitting JSON data

I'm encountering an issue with jQuery displaying a response after submitting data using JSON. Below is my HTML code: <input required="" width="100%" name="category_id" id="category_id" class="form-control"> <input required="" width="100%" ...

An issue with Rails 3 ajax call resulting in ActionView::MissingTemplate error

Currently, I am attempting to perform an ajax call without needing to return any data, or maybe just return a 200 status code. The error I encountered is: ActionView::MissingTemplate (Missing template .... Within the controller, this is my ajax method: ...

Utilize Mongodb straight from the client's perspective

Exploring the world of MongoDB, I am eager to learn how to retrieve data from the database using client-side technologies like jQuery, Angular, and HTML5 for my web application. Can I seamlessly integrate dependencies or plugins in Angular/jQuery to acce ...