Swap out the current image for a different one

When a user clicks on different image or color options, I want to change the main image displayed. Below are the links to the alternative images:

https://i.sstatic.net/DxJEb.jpg

This is the HTML code:

<div class="container">
<p class="img-main">
<a href="#" class="overlaybox-img">

<img src="http://coldcoffee.jp/resources/upload/products/thumbnail2/HM10-T-1004-WH.jpg">
</a></p>
<div id="colorsAndAltContainer">
<ul class="">

    <li class="defaultColor selected">
        <div class="inner">
            <div class="description">BLACK</div>
            <div class="rgbColor" data-color="000000" style="background-color: #000000"></div>
        </div>
    </li>
    <li>
        <div class="inner">
            <div class="description">WHITE</div>
            <div class="rgbColor" data-color="FFFFFF" style="background-color: #FFFFFF"></div>
        </div>
    </li>

    <div class="altImages">

    <ul class="alternativeImages">     
        <li class="selected">

        </li>
        <li>
            <img alt="T-Shirt and Jersey" class="alternativeImage"  src="http://s21.postimg.org/ep27oalqr/HM10_T_BACKLOGOLESS_1.jpg" width="54" height="54" >
        </li>
    </ul>
    </div>          

    </ul>
</div> 
</div>

CSS Code:

.container {
    min-height: 565px;
    width: 878px;
    margin: 0 auto;
    padding-top: 220px;
    position: relative; 
}

body{
    background-color: #000;
}
.img-main {
    margin-bottom: 10px;
    text-align: center;
    float: left;
    margin-top: 0px;
}
#colorsAndAltContainer {
    position: relative;
    top: 0;
    right: 0;
    width: 70px;
    height: 300px;
    float: left;
    margin-left: 6px;
}
.inner {
    cursor: pointer;
}
.description {
    display: none;
}
.rgbColor {
    border: 1px solid #cbcbcb;
    width: 13px;
    height: 13px;
}
.selectColor {
    float: left;
}

selectColor ul {
    float: left;
    margin-right: 6px;
}
ul {
    list-style: none;
    padding: 0;
    margin-top: 0px;
}
.altImages {
    position: absolute;
    width: 70px;
    bottom: 0;
    right: 0;
}
.alternativeImages {
    bottom: 0;
}
.alternativeImages li {
    cursor: pointer;
    margin-top: 6px;
}
img {
    display: block;
}

Answer №1

To start, make sure to give your T-shirt image a unique ID:

<img id="t-shirt" alt="T-Shirt and Jersey" class="alternativeImage"  src="http://s21.postimg.org/ep27oalqr/HM10_T_BACKLOGOLESS_1.jpg" width="54" height="54" >

Next, for your black and white buttons, add a data attribute containing the URL of the alternate t-shirt image:

<div class="inner" data-image-id="http://urltoblackimage.jpg"></div>

Using jQuery, you can then change the image source upon clicking the button:

$('div.inner').click(function() {
    var image = $(this).attr('data-image-id');
    $('#t-shirt').attr('src', image);
});

If needed, consider providing a more specific trigger name or adding an ID to the inner div class for clarity and to prevent any conflicts.

Answer №2

Here is an easy method to accomplish this using vanilla JavaScript.

function toggleImages(){
  if(document.getElementById("mainPic").src != "http://example.com/image1.jpg") {
    document.getElementById("mainPic").src = "http://example.com/image1.jpg";
    document.getElementById("smallPic").src = "http://example.com/thumbnail1.jpg";
  }else{
    document.getElementById("mainPic").src = "http://example.com/image2.jpg";
    document.getElementById("smallPic").src = "http://example.com/thumbnail2.jpg";
  }
     
  
}
.gallery {
min-height: 500px;
width: 800px;
margin: 0 auto;
padding-top: 200px;
position: relative; 
}

 body{
background-color: #fff;
 }
.img-main {
margin-bottom: 15px;
text-align: center;
float: left;
margin-top: 5px;
}
#colorsAndThumbs {
position: relative;
top: 0;
right: 0;
width: 60px;
height: 250px;
float: left;
margin-left: 6px;
}
.inner {
cursor: pointer;
}
.label {
display: none;
}
.colorSelect {
border: 1px solid #ccc;
width: 10px;
height: 10px;
}
.selectColor {
float: left;
}

.selectColor ul {
float: left;
margin-right: 6px;
}
ul {
list-style: none;
padding: 0;
margin-top: 5px;
}
.thumbImgs {
position: absolute;
width: 60px;
bottom: 0;
right: 0;
}
.altThumbImgs {
bottom: 0;
}
.altThumbImgs li {
cursor: pointer;
margin-top: 8px;
}
img {
display: block;
}
<div class="gallery">
<p class="img-main">
<a href="#"   class="image-box">

<img id="mainPic" src="http://example.com/image2.jpg">
</a> </p>
<div id="colorsAndThumbs">
<ul class="">

    <li class="default selected">
                    <div class="inner">
                        <div class="label">BLACK</div>
                        <div onclick="toggleImages();" class="colorSelect" data-color="000" style="background-color: #000"></div>
                    </div>
                </li>
                <li>
                    <div class="inner">
                        <div class="label">WHITE</div>
                        <div onclick="toggleImages();" class="colorSelect" data-color="FFF" style="background-color: #FFF"></div>
                    </div>
                </li>

    <div class="thumbImgs">

   <ul class="altThumbImgs">     
   <li class="selected">

        </li>
        <li>
            <img onclick="toggleImage();" id="smallPic" alt="Product Thumbnail" class="thumbnail"  src="http://example.com/thumbnail2.jpg" width="50" height="50" >
        </li>
     </ul>
                </div>          

                </ul>
     </div> 
       </div>

Answer №3

Below is a simple method that preserves your current code structure.

<script>
$().ready(function(){
$('#colorsAndAltContainer li').on('click',function()
{

  if($(this).find('.rgbColor').data('color') === "000000") 
  {
       $('a.overlaybox-img img').attr("src","http://s24.postimg.org/6khgqwwg5/HM10_T_1004_BK_1.jpg");
       $('.alternativeImage').attr("src","http://s4.postimg.org/6ualhzpex/HM10_T_BACKLOGOLESS_BK.jpg");
  }   
  else if($(this).find('.rgbColor').data('color') === "FFFFFF") 
  {
    $('a.overlaybox-img img').attr("src","http://coldcoffee.jp/resources/upload/products/thumbnail2/HM10-T-1004-WH.jpg"); 
    $('.alternativeImage').attr("src","http://s21.postimg.org/ep27oalqr/HM10_T_BACKLOGOLESS_1.jpg");
  }  
});

$('.alternativeImage').on('click',function()
{
  var smallImageUrl = $(this).attr("src");
  var mainImageUrl = $(".img-main img").attr("src");
  $(this).attr("src",mainImageUrl);  
  $(".img-main img").attr("src",smallImageUrl);
  $(".img-main img").css("width","300px");
});
});
</script>

Access the working demo here: http://jsfiddle.net/b2c5e19h/5/

Answer №4

To change the link of a specific <a> tag, first give it an id and then access it using JavaScript:

document.getElementById('idOfTag').setAttribute('href','someOtherImage.jpg');

This code can be included within a JavaScript function. Simply make the button or element that triggers the action listen for a click event and execute the function by adding onclick="yourFunctionsName().

You don't need to use jQuery for this task!

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

Adjust the camera in threejs to be positioned inside a different object

My goal is to adjust the camera controlled by trackballControl to match the position of an object. Currently, it's functioning correctly but as demonstrated in this example, each time the camera changes its position, the z value also changes, which i ...

JQuery Utilization: Constructing Queries - Techniques for Extracting Queries from Backend Code

Incorporating JQuery Query Builder into my ASP.net project. How can I retrieve the generated query from the code behind? Additionally, is there functionality to dynamically update one filter based on another selected filter? ...

What steps do I need to take in order to implement a basic ZeroClipboard copy-to-clipboard feature in jQuery on jsFiddle with just one click?

I'm having trouble implementing ZeroClipboard in a jQuery environment. My goal is to have the text within each div with the class copy copied when clicked. The following jsFiddle demonstrates the functionality with double click using the stable ZeroC ...

submit the data to the database

How can I successfully pass the value from the Ajax code to the database in this program aimed at displaying user details? There seems to be an error in the code for passing the value. What steps should I take to rectify this issue? function showUser() ...

What is the best way to locate the key with the greatest value in an array that is less than or equal to a certain

In my data structure, I have an array that maps user levels to the minimum points required for each level. Here's how it looks: $userLevels = array(0 => 0, 1 => 400, 2 => 800); The keys represent user levels and the values represent the min ...

ASP.NET Core Ajax response is empty

function addNewTeam() { var teamName = $("teamField").val(); $.ajax({ type: "POST", url: 'AddNewTeam', contentType: "application/json;", data: { team: "HELLO H ...

Creating a JavaScript function to automatically hide a dropdown menu after a specific duration

I'm currently working on a side menu that drops down when hovering over Section One within the <a> tag. I need some guidance on how to make the JavaScript code continuously check the state of the list after a set amount of time in order to autom ...

Ways to ensure that the dropdown content remains visible even after the mouse has exited the trigger element

There are three buttons arranged in a row, and when one is hovered over, dropdown content appears underneath all three buttons. However, the content disappears when the mouse moves down to it. Unfortunately, images cannot be posted inside yet** https://i.s ...

What is the syntax for linking to a different file in the frontmatter of a markdown file?

Currently, I am in the process of setting up Astro's Content Collections. One particular task I would like to achieve is referencing a specific author from my `authorCollection` within an article. In attempting to accomplish this, I considered utiliz ...

Using Node.js to implement GET, POST, and DELETE functionalities

I have embarked on the journey of learning Node.js and I find myself in a state of confusion. Could you please guide me on how to construct effective HTTP requests for the following scenarios: 1) Retrieve all galleries from the gallerySchema using a GET ...

Using AJAX for fetching and saving an object into a variable

I am dealing with two specific files in my project. The first one is called index.php, where the user initiates an AJAX request. The second one is called process.php, which is responsible for sending data back to the index.php file. function AjaxResponse( ...

Utilizing JQuery and Canvas to dynamically update a variable

Currently, I'm delving into learning JQuery for both fun and serious purposes. One of the mini projects I've been working on involves displaying the width of the window when the document loads. function window_width(window_w){ var window_w ...

Showing an image on a blurred background-image at the top of the webpage

Is it possible to overlay an image on top of another image, with the top image appearing blurred in the background? .background-image { background-image: url('https://images.pexels.com/photos/366968/pexels-photo-366968.jpeg?w=1153&h=750&a ...

strange occurrences in localToWorld transformation

Hello there! Currently, I'm working on a project where I'm generating a TextMesh using font geometry and placing it within an empty pivot object. My goal is to obtain the world coordinates of each vertex in the TextMesh so that I can manipulate ...

Explore accessing a PHP array with multiple dimensions using Jquery Ajax

I have a PHP script that runs a SQL query on my MSSQL Server instance and returns a good result. Now, I'm attempting to manipulate the result using $.ajax in jQuery, but it seems that accessing fields in an object table via "Object.field_name" is not ...

What is the best way to refresh a PHP function based on a JavaScript event?

I have a website where a div tag shows all the values from a SQL database using PHP. I want to reload this div tag with a JavaScript event, such as clicking on an HTML button. Is it possible to bring back all the values from the SQL database and display th ...

The setState function in React updates the value, however, when a form is submitted, it captures and

Encountering a problem with a modified field value not remaining on the form after submission. Working on a form where users can upload images. The image URL returned by the hosting service is saved in a state variable using this.setState({ im ...

A datatable was designed to set a background color for every row, regardless of any specified conditions for selecting which rows to apply

I have a challenge with setting background colors for rows in a datatable based on the data retrieved from the server. When fetching dynamic data through ajax, it is successfully displayed in the table. However, the color applied to all rows, regardless o ...

Transform the JSON format received from the API endpoint to make it suitable for use in the component

I'm working on a react-native app that fetches event data from a wordpress endpoint. Below is the JSON I receive from the wordpress API. How can I restructure it to fit into my calendar component? Where should I handle this restructuring in my app? ...

Customizing the Navigation Border-Bottom in WordPress

Currently, I am working on a project with this website. My main focus is on removing the border-bottom in the navigation bar for the last two right navigation points which are "DE" and "FR". Despite trying various CSS solutions, such as: #menu-item-394 { ...