Choose an image to display as the background image within a div

I'm developing an online poster creator and I could use some guidance on how to set an image as the background of a div element. I'm a bit lost on where to begin.

Currently, I have a div containing a selection of images and an empty div with just an ID.

This is my image selection div:

<div id="imgopt">
    <ol>
        <li>
            <img src="asset/img/template1.jpg">
        </li>
        <li>
            <img src="asset/img/template2.jpg">
        </li>
        <li>
            <img src="asset/img/template3.jpg">
        </li>
        <li>
            <img src="asset/img/template4.jpg">
        </li>
    </ol>
</div>

This is my Empty Div:

<div id="designPoster">

</div>

Essentially, I need help with writing the JavaScript code or getting some guidance on how to make it possible to set the background image of the empty div[id="designPoster"] by selecting an image from the div[id="imgopt"].

Answer №1

To achieve this using plain JavaScript instead of jQuery, follow these steps below. Please note that the image has been updated to show a functional demo.

var imageElements = document.querySelectorAll("#imgopt img");
var posterElement = document.querySelector("#designPoster");

for (var i = 0; i < imageElements.length; i++) {
  imageElements[i].addEventListener("click", changeBackgroundImage);
}

function changeBackgroundImage(e) {
  posterElement.style.backgroundImage = "url(" + e.target.src + ")";
  posterElement.style.backgroundSize = "contain";
  posterElement.style.backgroundRepeat = "no-repeat";
}
#imgopt img {
cursor: pointer;
width: 100px;
height: auto;
}

#designPoster {
width: 400px;
height: 157px;
background: #ccc;
}
<div id="imgopt">
  <ol>
    <li>
      <img  src="https://i0.wp.com/wptavern.com/wp-content/uploads/2016/07/stack-overflow.png?ssl=1">
    </li> 
    <li>
      <img  src="https://i0.wp.com/wptavern.com/wp-content/uploads/2016/07/stack-overflow.png?ssl=1">
    </li>
    <li>
      <img  src="https://i0.wp.com/wptavern.com/wp-content/uploads/2016/07/stack-overflow.png?ssl=1">
    </li>
    <li>
     <img  src="https://i0.wp.com/wptavern.com/wp-content/uploads/2016/07/stack-overflow.png?ssl=1">
   </li>
  </ol>
</div>;

<div id="designPoster"></div>

Best wishes for your coding endeavors!

Answer №2

Here is the solution to your inquiry:

$(function() {

   $('#imgopt img').on('click', function() {
     var imageSource = $(this).prop('src');
     $('#designPoster').css('background-image', 'url('+imageSource+')');  
     
   });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="imgopt">
  <ol>
    <li>
      <img  src="asset/img/template1.jpg">
    </li> 
    <li>
      <img  src="asset/img/template2.jpg">
    </li>
    <li>
      <img  src="asset/img/template3.jpg">
    </li>
    <li>
     <img  src="asset/img/template4.jpg">
   </li>
  </ol>
</div>

<div id="designPoster">

</div>

Answer №3

To set the background as the img src, you can use the following code:

$('#imgpot img').click(function(){
    $('#designPoster').css('background-image', `url(${this.attr('src')})`);
});

This code adds an event handler to each image tag within #imgpot. When clicked, it sets the background-image of #designPoster to the src attribute of the clicked image.

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

Utilizing object UUID keys to associate products in VueJS

Hey there, I've gone ahead and created an object with UUIDs but now I'm looking for a way to link these UUIDs to specific items. It seems like there needs to be some separation between the UUID and the rest of the object, however, my main issue i ...

The background image fails to load in ReactJS application

Usually, I have no trouble finding solutions to my problems, but this time I'm really stuck - and I apologize in advance if my question seems silly or trivial. I am currently working on a simple React app where I need to set a background image for th ...

Changing an object received as a prop in Vue.js

Is it acceptable to mutate values in a prop when passing an Object reference? In the process of developing a web application that involves passing numerous values to a component, I am exploring the most efficient method of handling value passing between c ...

Having trouble manipulating a web element within an expand grid while using the selenium web driver

I am attempting to modify the text of an element that is located within an expandable grid. (Navigate to URL www.treegrid.com/treegrid/www/ -> Edit the element under Order2, specifically MS Windows XP Pro OEM) I have attempted using jsClick without s ...

Begin the React counter with a starting value of two

Recently, I set up a new React application using the create-react-app command and ran a test with a render counter. Here is the code snippet: import React, { useState } from "react"; let render = 0; export default function App() { const [cou ...

Move a div by dragging and dropping it into another div

Situation Within my project, there is a feature that involves adding a note to a section and then being able to move it to other sections, essentially tracking tasks. I have successfully implemented the functionality to dynamically add and drag notes with ...

The submit button remains unresponsive, yet upon removing its JavaScript code, it functions smoothly

This is the content of my index.html file. It contains JavaScript code. However, there seems to be a problem with the JavaScript validation as the Submit button does not perform any action when clicked. Surprisingly, when I remove the JavaScript code, the ...

Show the current server time from ASP.NET in four distinct time zones using JScript

I am in the process of customizing a SharePoint master page by adding a unique header that showcases the current time across four different time zones. However, I am faced with the challenge of determining the appropriate server-side time to use for accura ...

Converting HTML Javascript to JAVA with the help of Selenium

Can someone help me extract the value of h1 as a string using selenium? Check out the HTML javascript snippet below- <script type="text/javascript"> $(window).load(function() { var $windowHeight = $(window).height() -12; $(" ...

Top method for inverting the sequence of list elements

I've got this Skype history saved as HTML, with 20,000 list items < li > in reverse order. How can I swap them around so that the first item becomes the last and vice versa? Is there a PHP solution for this, or is there a simpler way using spec ...

Leverage the power of HTML5 localstorage in order to maintain the toggle state of jQuery even

After discovering the HTML5 "localstorage" function, I decided to try implementing it in combination with jQuery toggle to keep a div in its most recent state even when the page is refreshed. It seems like a more modern alternative to using cookies. Howeve ...

Safari displays text in a noticeably bigger font size compared to other browsers

I'm currently working on a website and have noticed that the fonts appear larger on Mac's Safari compared to other browsers. We are using the 'Open Sans' font from Google Fonts for our website. For example, here is a CSS snippet for ti ...

What is causing the error "Expected an assignment or function call and instead saw an expression" to occur in this situation?

I am encountering an error that says "Expected an assignment or function call and instead saw an expression" at the second useEffect. The socket port is being detected correctly, but I suspect my usage of socket.on may be incorrect. The socket server initi ...

The function app.post in Express Node is not recognized

I decided to organize my routes by creating a new folder called 'routes' and moving all of them out of server.js. In this process, I created a file named 'apis.js' inside the routes folder. However, upon doing so, I encountered an error ...

Having trouble with OBJ model loading in Three.JS

Having trouble loading obj models and encountering a CoffeeScript error: loader = new THREE.OBJLoader manager if loadedModels.diamondRing == null loader.load "obj/diamond/ring1.obj", (object) -> object.traverse (child) -> ...

Incorporated video content directly onto my website

Can anyone provide guidance on how to embed a video from the following site? I attempted to copy the link in view source mode, but the video address seems to change after a certain period of time. Would greatly appreciate any assistance with this issue. ...

In Vue.js, it is not possible to modify a component variable within a callback function

I have implemented a custom Login.vue component using vue.js to allow users to log in to my application through AWS Cognito. The authentication process is handled by the ___.authenticateUser() method, which initiates a session with Cognito. Below is the co ...

Tips for dividing a single row retrieved from a MySQL database that has been converted with json_encode so that it can be shown in

Looking to extract data from a MySQL query result in one PHP page and transfer it to a separate page with JavaScript. Here is my attempt so far: I am aiming to retrieve specific values from the selected row in the MySQL table and populate them into #event ...

Display a string of text containing multiple interactive links

I have a table and I want to create an interactive effect where, upon mouseover or click of certain elements, text will appear next to it. This text may contain multiple lines and clickable links within the content. For instance, in the table generated by ...

Utilizing RxJS finalize in Angular to control the frequency of user clicks

Can someone provide guidance on using rxjs finalized in angular to prevent users from clicking the save button multiple times and sending multiple requests? When a button click triggers a call in our form, some users still tend to double-click, leading to ...