Update the picture displayed in the parent div when it is in an

My code currently changes the image when a parent div is in an active state, but I'm struggling to figure out how to revert it back to the original image when clicked again. I attempted to use 'return false' at the end of the script, but it didn't have the desired effect.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card egg" data-img="https://data.imgtools.co/output/tool/preview/400x400/face-extractor.png">
 <div class="card-image">
  <img src="https://play-lh.googleusercontent.com/IeNJWoKYx1waOhfWF6TiuSiWBLfqLb18lmZYXSgsH1fvb8v1IYiZr5aYWe0Gxu-pVZX3"/>
 </div>
</div>
$('.egg').click(function(){
  $(this).toggleClass("active");
  var new_src = $(this).attr('data-img');
  $(".card-image img").attr("src",new_src);
});

Answer №1

If you want to keep track of the original img src before toggling its state, simply update the same data attribute where you are storing the alternate image.

In this demonstration, I have optimized the way you select the img element by specifically targeting the img child within the clicked .egg div:

$('.egg').click(function() {  
  const new_src = $(this).attr('data-img');  
  const curr_src = $(this).find('.card-image img').attr('src');
  $(this).attr('data-img', curr_src);
  
  $(this).toggleClass("active");  
  $(this).find('.card-image img').attr("src", new_src);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="card egg" data-img="https://data.imgtools.co/output/tool/preview/400x400/face-extractor.png">
  <div class="card-image">
    <img src="https://play-lh.googleusercontent.com/IeNJWoKYx1waOhfWF6TiuSiWBLfqLb18lmZYXSgsH1fvb8v1IYiZr5aYWe0Gxu-pVZX3" />
  </div>
</div>

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

"Troubleshooting a JSON structure containing a complex array of objects with multiple layers

I've structured a complex array with JSON objects to allow users to customize background images and create unique characters. Below is the main code snippet: var newHead; var newBody; var newArm; var masterList = [ { {"creatureName":"Snowman ...

Collaboration of Bootstrap components

I am facing an issue with two divs that are supposed to be displayed side by side in a normal browser. However, when the browser window is resized, the first div loses its height and the second div overlaps into it. I attempted to set the body's min h ...

Let's update the VUE app's development server to point to my-testing-web-address.com instead of the default localhost:

I am working on a VUE application and I am trying to run it on an external link instead of localhost. I attempted to configure a vue.config.js devServer: { host: 'http://my-testing-web-address.com', port: 8080, ... } and adjusted t ...

What purpose does the div tagged with the class selection_bubble_root serve in Nextjs react?

Just starting out with Nextjs and setting up a new Next.js React project. I used create-next-app to initialize the code base, but then noticed an odd div tag with the class 'selection_bubble_root' right inside the body. Even though its visibility ...

Utilizing the fetch() method in Vuex to obtain a restful API

Struggling to integrate my API data through Vuex, I am in dire need of a reliable guide or perhaps someone who can assist me with this task. Previously, without using Vuex, all my requests functioned flawlessly. However, now I'm unsure about the neces ...

Load the iframe element only when the specified class becomes visible within the container div, without relying on jQuery

I am facing a unique challenge where the performance of my page is significantly impacted by loading multiple iframes. These iframes are contained within popup modals, and I would like to delay their loading until a user clicks on the modal. When the mod ...

Ajax not functioning after submission of form

I currently have this code snippet: $('#my_form').submit(function () { setTimeout(function () { console.log('1'); $.ajax({ type: "GET", url: "/CorrectUrl/CorrectUrl", ...

Switch off JavaScript beyond the parent element

Struggling with implementing an event to toggle a div using an element located outside of the parent container. I am attempting to achieve the same functionality by targeting elements beyond the parent structure utilizing a span tag. Any assistance on th ...

Is it possible in Vuetify 2 to align the items within the expansion of a v-data-table with the headers of the main component?

I am currently working on rendering a v-data-table where the expandable section serves as a "panel" title and I want the data inside the expansion to align with the headers set at the root level. Despite my efforts, I have not been able to find a way in th ...

Determine the total number of selected items in MagicSuggest when it loses focus

I have been working with MagicSuggest and I am currently facing an issue where I need to retrieve the length of selections on a blur event. Interestingly, my code functions perfectly fine when a new selection is added using the ENTER key, but it fails when ...

Bootstrap Modal Fails to Display Image Within Its Container

I'm currently working on my e-commerce website, where I'm attempting to implement a feature that allows users to view product images in a modal for a closer look. The product page contains a list of images, and when a user clicks on one, it shoul ...

CSS: Stack elements vertically based on their height (column-wise)

Looking for some help with designing a menu where the list items float in columns instead of rows. For example, This is how my current menu looks like: I want to change the layout to look like this: My code for the list items is as follows: .mnu-third ...

Retrieve the Vue.js JavaScript file from the designated static directory

This is my inaugural attempt at creating a web application, so I am venturing into Vue.js Javascript programming as a newcomer. I have chosen to work with the Beagle Bootstrap template. Within my Static folder, I have a file named app-charts-morris.js whi ...

What is the best way to create a dropdown menu within an iframe that appears on top of all other frames?

The code snippet below is from my frameset.jsp file: </head> <iframe width="100%" src="mail_frame.html"></iframe> <iframe width="105px" height="100%" src="sidenav.html" id="leftnav" name="leftnav" ></iframe> ...

Formatting text to automatically continue onto the next line without requiring scrolling through long blocks of

I have a unique Angular project with a terminal interface that functions properly, maintaining a vertical scroll and automatically scrolling when new commands are entered. However, I am struggling to get the text within the horizontal divs to wrap to the ...

What is the purpose of making a "deep copy" when adding this HTML content?

My canvas-like element is constantly changing its contents. I am attempting to execute a function on each change that captures the current content and adds it to another element, creating a history of all changes. window.updateHistory = func ...

Enhance the usability of input-group-addon elements in Bootstrap by incorporating focus and validation states, rather than focusing

When using Bootstrap, focusing on an input activates a blue border and box shadow to show where the user's attention is. If there are validation states such as error, warning, or success, a red, yellow, or green border will be added accordingly. An ...

`Finding the nodejs API route for displaying images from a database`

How can I successfully display an image from the database without getting a string of question marks instead? Click here to see the issue >>> When attempting to directly call the API using the provided link, the following result is returned: {&qu ...

Adding custom fields to the user model in MongoDB using Next Auth during login is not possible

When a user logs in via next auth, I am looking to include custom fields to the default user model. I followed the instructions provided in the official documentation at https://next-auth.js.org/tutorials/typeorm-custom-models. Here is the code snippet: ...

Exporting JSON data as an Excel file in AngularJS, including the option to customize the fonts used for the

Currently, I am working on a project where I need to convert JSON data to an Excel file using JavaScript in combination with AngularJS. So far, I have successfully converted the JSON data to CSV format. However, I faced issues with maintaining the font s ...