Combining Images with Jquery: A guide to layering multiple images on top of each other

In this code snippet, I have a webpage that allows users to customize their own shirt. By selecting options such as "Male/Female," the '#shirt' section dynamically displays an image of the constructed shirt by layering PNG images on top of each other. For instance, choosing a base color like 'blue' will show an image of a blue shirt. Then, selecting a body stitching option like "ribbed" adds another image on top of the base color image with ribbing detail. The issue I'm facing currently is that each new image replaces the previous one instead of stacking on top of it. Other functionalities like displaying options based on previously selected choices are working correctly.

<div id="gender" class="diy-box">
    Choose Gender<br>
    <input type="radio" name="gender" data-id="" value="male" /><label>Male</label><br>
    <input type="radio" name="gender" data-id="" value="female" /><label>Female</label>

</div>

<section id="displaysection">

    <div id="male" class="desc gender diy-box">

        Choose Body Color<br>
        <input type="radio" name="male" data-id="105" value="" /><label>Blue</label><br>
        <input type="radio" name="male" data-id="120" value="" /><label>Black</label><br>
        <input type="radio" name="male" data-id="145" value="" /><label>White</label>

    </div>

    <div id="female" class="desc gender diy-box">

        Choose Body Color<br>
        <input type="radio" name="female" data-id="107" value="" /><label>Blue</label><br>
        <input type="radio" name="female" data-id="211" value="" /><label>Black</label><br>
        <input type="radio" name="female" data-id="212" value="" /><label>Pink</label>

    </div>

</section>

<div id="body_stitching" class="diy-box">

    Body Stitching Type<br>
    <input type="radio" name="body_stitching" data-id="" value="body_stitching_plain" /><label>Plain</label><br>
    <input type="radio" name="body_stitching" data-id="" value="body_stitching_rib" /><label>Rib</label>

</div>

<section id="displaysection">

    <div id="body_stitching_plain" class="desc body_stitching diy-box">

        Plain Stitching<br>
        <input type="radio" name="body_stitching_plain" data-id="324" value="" /><label>Blue</label><br>
        <input type="radio" name="body_stitching_plain" data-id="325" value="" /><label>Red</label>

    </div>

    <div id="body_stitching_rib" class="desc body_stitching diy-box">

        Rib Stitching<br>
        <input type="radio" name="body_stitching_rib" data-id="" value="black" /><label>Black</label><br>
        <input type="radio" name="body_stitching_rib" data-id="" value="green" /><label>Green</label>

    </div>

</section>

<div class="clear"></div>

<div id="shirt"></div>

<div id="pricefield" style="float:right"></div>

<script>

$(document).ready(function() {
    $("div.desc").hide();

    var data = {
        "105" : { img: "http://oceandrive.localhost/images/diy-images/105.png", label: "Color 1", price: "100" },
        "120" : { img: "http://oceandrive.localhost/images/diy-images/120.png", label: "Color 2", price: "110" },
        "145" : { img: "http://oceandrive.localhost/images/diy-images/145.png", label: "Color 3", price: "120" },
        "107" : { img: "http://oceandrive.localhost/images/diy-images/107.gif", label: "Color 4", price: "130" },
        "211" : { img: "http://oceandrive.localhost/images/diy-images/211.png", label: "Color 5", price: "140" },
        "212" : { img: "http://oceandrive.localhost/images/diy-images/212.png", label: "Color 6", price: "150" },
        "324" : { img: "http://oceandrive.localhost/images/diy-images/324.png", label: "Color 7", price: "160" },
        "325" : { img: "http://oceandrive.localhost/images/diy-images/325.png", label: "Color 8", price: "170" },
    };


    $('input[name]').click(function() {


        var value = $(this).val();   // picks the value of the radio button

        if(value=='male' || value=='female') {
            $("div.gender").hide('slow');
            $("div.gender input:radio").removeAttr('checked');
        }

        if(value=='body_stitching_plain' || value=='body_stitching_rib') {
            $("div.body_stitching").hide('slow');
            $("div.body_stitching input:radio").removeAttr('checked');
        }

        $("#" + value).show('slow');  // targets the div with the radio button value selected



        if(this.checked) {

            //var value = $(this).val();
            var value = $(this).data('id');

            if (data[value] != undefined)
            {

                var html = '';
                html = html + '<img style="z-index:2;" src="'+data[value].img+'" />';
                $('#shirt').html(html);

                var html = '';
                html = html + '- '+data[value].label+' - '+data[value].price+' NT<br>';
                $('#pricefield').html(html);

            }

        }

    });

});

Answer №1

To begin, determine the desired order of your images. Based on the code provided, it seems you have identified two levels (though more can be added if necessary):

  1. Base
  2. Body stitching

Next, assign a z-index to each level and create corresponding <div> elements for them. These <div> elements should be styled with absolute positioning, like this:

<div id="baseImage" style="z-index:1; position: absolute;"></div>
<div id="stitchImage" style="z-index:2; position: absolute;"></div>
...

It may also be beneficial to specify the width and height of each <div> to match the dimensions of your images.

Finally, utilize jQuery to properly position each <div> layer on top of the base image.

$("#stitchImage").offset($("#baseImage").offset());

When updating images, simply implement the following code:

$("#stitchImage").html("<img src='" + src + "' />");

Keep in mind that utilizing a placeholder image is advisable to allow users to view lower layers before selecting higher ones.

Answer №2

rather than utilizing:

$('#shirt').html(html);
('#pricefield').html(html);

opt for the .append(...) technique.

$('#shirt').append(html);
('#pricefield').append(html);

jQuery .append()

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

What is the best way to address the issue of images exceeding the height limit in my dynamic views?

Query: Why is the image height increasing significantly in this scenario? Despite implementing the solution provided in the aforementioned question, the issue has resurfaced. Do you believe the problem lies in the frontend or backend? I am considering cre ...

CSS positioning alignment

Could someone please explain to me why changing the position to relative causes the "facebook and Facebook helps you connect and share with the people in your life" text to display at the top of the page? I've only been studying CSS for three days. Th ...

Tips for arranging two divs from a single column to display side by side on smaller screens instead of stacked on top of each other

My knowledge of CSS, HTML, and bootstrap is quite limited. I'm trying to figure out how to split a single column on a large screen into two columns on a smaller screen so that the content in two divs appears side by side instead of stacked on top of ...

Using AJAX and Perl to dynamically update HTML content

Currently, I am attempting to dynamically update a div on my website using ajax and perl. The current implementation I have sort of works but needs improvement. HTML: <h2 id="cpu">--</h2> JS/ajax call: $.ajax({ type: 'GET&apos ...

Create an interactive table in your WordPress website that adjusts to different screen sizes

Having scoured numerous posts on responsive tables in this stack, I am still unable to find a solution to my specific issue. It's quite possible that I didn't know what exactly to look for, hence my resorting to posting a question here. The crux ...

Codeigniter 3 and JQuery seamless refresh: A dynamic duo

I'm currently attempting to utilize the following code: setInterval(function() { $('#myDiv').load('contentToLoad.php');}, 5000); while working with CodeIgniter. My attempt so far has been: setInterval(function() { $('.image ...

Sending a jQuery variable through AJAX

Currently encountering an issue where I have to pass a jQuery variable through an ajax request. Upon sending two jquery variables and receiving a bulk of irrelevant output in the ajax.php file, I am faced with the task of extracting only the values of tho ...

Prevent screen rotation on any mobile device's browser

Is there a way to lock the screen orientation to landscape for all mobile device browsers when accessing a website? Searching online yields results mainly focused on app development, but I'm interested in achieving this for websites. I've found ...

Resolve the issue of text overflow in PrimeNG Turbo Table cells

When utilizing Primeng table and enabling the scrollable feature, the table is expected to display a scrollbar while ensuring that the text within the cells does not overflow. Unfortunately, this expected behavior is not occurring. To see an example of th ...

Conceal the table row if the table data does not have any text within it

I need a way to hide rows in a table where the corresponding cells do not contain "text2". Initially, I tried using this code: $('td:contains("text2")').parent().toggle()})) Although this successfully hides rows with cells containing "text2", I ...

Create an HTML component that expands to fill any leftover space on the page, without using flex

In my current situation, I have two elements positioned side by side with dynamic widths based on their content. The element on the right needs to fill up as much vertical space as possible without a set width. I am looking for an alternative to flexbox d ...

Using jqgrid to customize column header tooltips which are distinct from the actual column label

From what I gather, there are multiple methods for setting distinct column header tooltips. At the moment, my approach involves using jQuery's .attr() to set the tooltips. I'm curious if there is a more streamlined way to save the custom header ...

Is there a way to use Jquery to determine if a parent div contains a scroll

I'm trying to find a jQuery example that checks if any parent div has a scroll bar, but I can't seem to locate a helpful one. Here is the code snippet I am working with: <div> <div class="heading"> <div class="visit ...

dynamic dropdown displaying colors for selection

Using a bootstrap form to add a printer involves selecting the material and color. The dynamic dropdowns are functioning correctly, but it is necessary to display the selected color for user clarity. Please guide me on how to pass the color along with its ...

Lost variable during the ajax call

Encountering a peculiar issue while attempting to pass a variable as a parameter to a nested ajax request callback: $('form').on('submit',function(e){ $.ajaxSetup({ header:$('meta[name="_token"]').attr('conte ...

Updating the total on the Infusionsoft order form can be achieved using either Jquery or custom code

Is there a way to automatically calculate and update the total amount on the order form based on user input in two quantity fields? The price should increase as the user adjusts the quantity. I've been searching for a solution, but haven't found ...

PHP code for determining the monthly subscription package cost

I have recently launched an e-commerce website that offers lunch and dinner delivery services. I am reaching out for help as I have encountered a problem with calculating prices based on different packages/plans available on the website. 1. Weekly 2. Mo ...

Tips for spinning a div with jQuery as it animatesRotate a div and animate it simultaneously using

Currently, I have a piece of code that enables my div element to move and change its size. $(document).ready(function(){ $("#box").animate({ top: "250px", left: "500px", width: '300px', height: '250px& ...

Tips for adjusting the indentation of list items with CSS while working with floating blocks

Recently, I encountered a peculiar situation while working with floating images in a document. It seems that the list items indentation is being determined by the 'red line' rather than the expected 'green' one. I'm puzzled as to ...

Clipped Words & Silhouettes

I'm having trouble ensuring the text in this particular example displays correctly. I am experiencing challenges with the clipping of text and shadows on certain letters, and I'm struggling to identify the root cause as well as the solution. In ...