Adjusting the image in JavaScript and jQuery

Within a group of span elements, there are img tags nested inside.

<span id = "span1" class="span-class">
    <img src="img.jpg"/>
</span>
<!--Several more similar span elements -->
<span id = "span123" class="span-class">
    <img src="img.jpg"/>
</span>

The image img.jpg is the default image displayed when the page first loads. I want this default image to be replaced with first_clicked_img.jpg when I click on a span for the first time. Subsequently, I would like first_clicked_img.jpg and second_clicked_img.jpg to switch places each time I click on a different span. How can this functionality be achieved using jQuery, or if simpler, with pure js?

Answer №1

To make the functionality work, attach an `onclick` event to your `span` element. When the event is triggered, you should hide the `#span1` and display the `#span123`.

Similarly, for the reverse action, when clicking on the `#span123`, hide `span123` and show `#span1`.

Best regards

Answer №2

$(".span-class").click(function() {
    var image = $(this).find("img");
    var updated_src;
    switch (image.attr("src")) {
        case "original_img.jpg":
        case "alternate_img.jpg":
            updated_src = "new_img.jpg";
            break;
        case "new_img.jpg":
            updated_src = "alternate_img.jpg";
            break;
    }
    image.attr("src", updated_src);
});

Answer №3

It seems like you're trying to achieve the functionality where the image changes to first_clicked_img on the first click and then to second_clicked_img on the second click. Here's a solution that can help you with this:

let clicks = 0;
$('span').on('click', function(){
    if(clicks === 0){
        clicks = 1;
        $(this).find('img').attr('src','first_clicked_img.jpg');
    } else if(clicks === 1){
        clicks = 0;
        $(this).find('img').attr('src','second_clicked_img.jpg');

    }
});

I have reset the value of clicks to 0 in the second if statement so that subsequent clicks on span will toggle between the two images as per your requirement. Does this solve your query?

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

Clear a form field automatically in React using react-hook-form when a new value is entered in another field

Featuring this particular component: import { yupResolver } from '@hookform/resolvers/yup'; import { useForm } from 'react-hook-form'; import * as yup from 'yup'; import { Input, TabsGroup, Button } from './ui-components ...

Class-based Button Transition Effect failing to operate as intended

I want to trigger these 3 events simultaneously when a form is filled out, all initiated by the same button. I have been able to make it work using 3 classes named: "draw dj", which represents the first event "draw1 dj", which signifies the 2nd event "d ...

IE doesn't seem to support framesets, while Mozilla browsers handle them just fine

Can anyone help with this code that works in Mozilla but not in Internet Explorer? The situation is urgent. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> <html lang="en" xmlns= ...

How to use jQuery to recursively assign numbered classes to groups of div elements

I am dynamically grouping a fixed number of divs from an array (e.g. 4 in each group). The total number of .item divs retrieved from the array is uncertain... I need to recursively assign the same class to these groups of wrapped divs: <div class="wrap ...

Attempting to populate getElementByID using JavaScript function from CodeBehind proves unsuccessful

When a button is clicked on a form, I need to fill in hidden elements that will be posted. The script below should set the values for these hidden fields: <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> < ...

Trying to update React and Electron, encountering the error message "global is not defined"

I have an Electron + React app that has not been updated in a couple of years, initially utilizing the following packages: "@rescripts/cli": "^0.0.13", "@rescripts/rescript-env": "^0.0.11", "electron": &quo ...

Issues arise when the Slick functionality fails to load following an ajax request

I've come across a situation similar to the one on this post. I'm having trouble getting my slick carousel to work after a successful ajax call. Despite trying all the solutions provided, it's still not functioning as expected. The code for ...

Create a circular motion animation from scratch

Looking to create an animation resembling a "firework" that bursts around a circular image, with 10 rays spaced evenly like wheel spokes. Each ray extends, the tail catches up to the head, and then disappears. The first ray originates from the bottom: Cod ...

Total sum displayed within the Apex interactive grid

In my APEX application, I am utilizing the Interactive grid feature. In the first row, I entered the value as 1000.00 and in the second row as 500. My goal is to calculate the total value of 1,500.00 and display it in a Hidden item. Currently, I am able t ...

Utilizing Vue.js and Webpack to Handle Requests for Multiple Incorrect Resource Links

After utilizing Vue.js single file components to construct a website and appreciating the modular approach, I've encountered an issue. The browser appears to be requesting multiple versions of resources instead of just one URL for each. HeaderBar.vue ...

Contrast between sourcing a file from the current directory versus from the node_modules folder

Why does the typescript compiler accept importing from a JS file in the local directory but raises an error when importing from node_modules? Code: import { t2 } from "./t1.js" t2.hello(); import { mat4 } from "./node_modules/gl-matrix/esm ...

Retrieve all checkboxes that have been altered using jQuery

There are numerous checkboxes on my page, each in a separate cell. My goal is to retrieve the checkboxes that have been altered from their original state. The original value is stored in an attribute named "data-original-value" within a span that encloses ...

Decomposition of words in VueJS based on numerical values

Is there a way to handle word declension based on the number of items in VueJS? For example, displaying "0 skins", "1 skin", "2 skins", "3 skins", "4 skins", "5 skins", and so on. I currently have a basic code snippet with hardcoded text: <div class=&q ...

Creating fresh CSS by extracting essential selectors from an existing CSS file using Javascript

Is there a method to develop a mini JavaScript function that can parse an HTML document, extract specific selectors from a lengthy CSS file that contains over 2000 lines, and create a new CSS file with only the necessary styles? ...

When utilizing jQuery in HTML, the Marquee will bounce back upon reaching the end

My issue is that when I use a regular marquee, the text simply goes to the end and does not bounce back to the start as soon as it reaches the end of the div. Instead of using a normal marquee, I am looking to achieve this desired effect by utilizing jQue ...

What is the best way to display or hide specific tables depending on the button chosen?

Being fairly new to JavaScript, I find myself unsure of my actions in this realm. I've successfully implemented functionality for three links that toggle visibility between different tables. However, my ideal scenario would involve clicking one link t ...

Transform website code into email-friendly HTML code

Is there any software available that can convert web HTML and CSS files to email HTML with inline CSS? This would allow the email to be viewable on various email clients such as Outlook, Thunderbird, Gmail, Yahoo, Hotmail, etc. I want to write my code lik ...

Saving a value in a service using AngularJS

I am facing an issue with passing a variable into a service that needs to be accessed from multiple states within my application. I have created a service and attempted to pass a variable from a controller into the service in order to access it from anothe ...

Error encountered when attempting to load files from the same domain due to CORS restrictions

I'm currently developing a website at and I am trying to load the content of an HTML file into an element. I have specified the element as $('.about-us-first-col') and I am loading the content using the code: $('.about-us-first-col&apo ...

Is there a way to identify if the parent page has completed loading while within an iframe?

Is there a way to detect properties or events within the iframe that can help determine this? The src of the iframe and the parent page belong to different domains. ...