Change the class to update the image when clicked using jQuery

Although I've researched several articles and answers on Stack Overflow, none of them have addressed my question thoroughly. Admittedly, I am quite new to jQuery and unsure about how to proceed.

I am working on an HTML landing page where I aim to display multiple images that change when clicked, toggling between two different images. Essentially, clicking on an image should replace it with another one, and vice versa.

Here is what I have accomplished so far:

<div class="santa">
  <img class="show" src="images/santa.png" alt="">
  <img class="hide" src="images/bubble.png" alt="">
</div>
.hide { display: none; }
.show { display: block; }

The desired behavior is for the default image santa.png to be displayed initially, and upon clicking, it should switch to bubble.png. This means that the default class should be show, switching to hide once clicked, and vice versa for santa.

Thank you in advance for your help!

Answer №1

A straightforward way to achieve this is by using the toggle() function on both the visible and hidden images when either one is clicked. This will toggle the display state of both elements at the same time:

$('.hide, .show').click(function() {
  $(this).closest('div').find('.hide, .show').toggle();
})
.hide { display: none; }
.show { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="santa">
  <img class="show" src="images/santa.png" alt="Santa">
  <img class="hide" src="images/bubble.png" alt="Bubble">
</div>
<div class="santa">
  <img class="show" src="images/santa.png" alt="Santa2">
  <img class="hide" src="images/bubble.png" alt="Bubble2">
</div>

If you wish to actually change the class attributes of the elements, you can utilize toggleClass() instead:

$('.hide, .show').click(function() {
  $(this).closest('div').find('.hide, .show').toggleClass('hide show');
})
.hide { display: none; }
.show { display: block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="santa">
  <img class="show" src="images/santa.png" alt="Santa">
  <img class="hide" src="images/bubble.png" alt="Bubble">
</div>
<div class="santa">
  <img class="show" src="images/santa.png" alt="Santa2">
  <img class="hide" src="images/bubble.png" alt="Bubble2">
</div>

Answer №2

For those just starting out, I recommend mastering vanilla JavaScript before delving into libraries like jQuery.

Here is a pure JavaScript approach. Enjoy!

let santaimg = document.getElementById('santa');
let bubbleimg = document.getElementById('bubble');

santaimg.onclick = showBubbleHideSanta;

function showBubbleHideSanta() { 
 santaimg.classList += " hide";
 //santaimg.classList -= "show";
 bubbleimg.classList -= " hide";
 //bubbleimg.classList += "show";
}
.show {
  display:block;
}
.hide {
  display:none;
}
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/49/Jonathan_G_Meath_portrays_Santa_Claus.jpg/220px-Jonathan_G_Meath_portrays_Santa_Claus.jpg" id="santa" class="show"/>
<img src = "https://sophosnews.files.wordpress.com/2017/05/shutterstock_296886146.jpg?w=780&h=408&crop=1" id="bubble" class="hide"/>

Answer №3

Here is a solution for displaying two images using HTML, CSS, and JavaScript:

HTML

<div class="santa">
                <img class="show" src="http://via.placeholder.com/350x150" alt="img">
                <img class="hide" src="http://via.placeholder.com/250x150" alt="img">
 </div>

CSS

.show{
    display:block;
 }
 .hide{
    display:none;
 }
 img{
    max-width:100%;
    height:auto;
    cursor:pointer;
 }

JS

 jQuery('.show, .hide').click(function() {
      jQuery('.show, .hide').toggle();
    });

Give it a try! Thanks!

Answer №4

To easily toggle the visibility of an element, I recommend using .hide() and .show() methods provided by jQuery. This eliminates the need for additional CSS styles.

"The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value" http://api.jquery.com/hide/

Here is a sample scenario:

HTML

<div>
    <img class="santa_img" src="images/santa.png" alt="santa">
    <img class="bubble_img" src="images/bubble.png" alt="bubble">
</div>

JS (JQuery)

$(".santa_img").click(function(){

    $(".santa_img").hide();
    $(".bubble_img").show();

})

$(".bubble_img").click(function(){

    $(".bubble_img").hide();
    $(".santa_img").show();

})

$(".bubble_img").hide(); //Hidden by default

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

Include jQuery from a different directory

A Closer Look at the Symptoms Encountering issues with jQuery file paths can lead to undefined errors. With jQuery located in different directories, such as the root or child directory, certain JavaScript files may fail to recognize its presence. The sol ...

Firefox presents a compact box positioned between the images

When attempting to use flags as a way to switch between languages, I encountered an issue in Firefox where a small box appears between the images on the Hebrew site. In Chrome, everything works fine. I implemented the following code: <div class="flags ...

Creating Bootstrap Popover dynamically on a jQuery DataTable is a straightforward process that can enhance user experience

I am currently populating a table with data retrieved from an ajax call. The filling process is done through the use of append method as shown below: var table = //something //loop through ajax response objects table.append('<tr><td>&apo ...

i18next backend failing to load files

Hey there! Currently, I am implementing i18next within my Node JS Application. Below is the configuration code for i18next: const i18nextBackend = require('i18next-node-fs-backend'); i18n .use(i18nextBackend) .init({ fallbackLng: &apos ...

Is there a specific method that can be implemented in Node.js to compare two strings and identify the common words or letters?

Looking for a solution: var str1="CodingIsFun"; var str2="ProgrammingRocks"; Is there any function that can provide a true value or flag in this case? ...

Adjusting the size of icons to fit within a container

I need a div that can display up to 7 icons, depending on certain selections. These icons are from ionicons library. Here is the current code snippet: <div class="item item-text-wrap" style="text-align:center;"> <button class="button" style=" ...

JavaScript alert: element does not exist

Check out my code snippet below. The inline JavaScript alert works fine, but the external one isn't firing. Every time I reload the page, I'm greeted with a console error message saying "TypeError: tileBlock is null". Any suggestions on how to re ...

Can anyone explain why I keep encountering an endless loop when using react hooks?

Having a bit of trouble with fetching data from a JS file that is mimicking an API with some endpoint methods. When I console log the data, everything seems fine, but for some reason, I keep running into an infinite loop when using hooks. I've tried t ...

Using recursion in JavaScript to determine if a given number is prime

I am feeling a bit puzzled about how to tackle this issue. My goal is to have all prime numbers return as true, and if not, then false. I noticed that my current logic includes 2, which returns 0 and automatically results in false because 2 has a remainder ...

Transforming intricate JSON data into a structured table format

I'm struggling to transform the nested JSON data into an HTML table, but I keep encountering an error. I'm uncertain about where I may have made a mistake. Could it be related to how I am trying to access the array within the object? Here' ...

What is the method to retrieve data in Vue when utilizing arrow functions?

When utilizing Vue and arrow functions in methods, we encounter the issue that arrow functions do not have a this keyword. The question then arises of how to access data properties such as list or object. export default { data() { return { list ...

What is the most efficient way to organize a dynamic array with jQuery?

In my jQuery code, I have created two empty arrays and used AJAX to assign values to them. The issue is that the values assigned by AJAX are random, so I need to display them in an efficient way. Here's the code snippet I'm using: Code:- <se ...

Using React to trigger a child component's function upon clicking a tab

I need assistance with creating a React app that includes two tabs (Tab1, Tab2). When Tab2 is clicked, I want a message to appear in the console saying 'Function A is called'. Unfortunately, the code I have currently does not display the message ...

Is it possible to extend jQuery TypeWatch for handling empty input?

I developed a custom autocomplete feature using AJAX and I'm looking for a way to track the search input as users type. Currently, I'm utilizing TypeWatch but it has a drawback - if users delete their input resulting in an empty field, the search ...

Enhancing the appearance of text in an article by using hover effects, while ensuring the link is attached to the

As I work on the design of my website, I am faced with a challenge involving elements that have links attached to them. I want visitors to be able to click anywhere on the article and be directed to a specific page. The code snippet I currently have is as ...

Header and footer set in place with customizable height paired with a dual-module sidebar

I'm working on a layout that includes a fixed footer and header. My goal is to make the height of the "info-box" div variable, while having the "scrolling-div" fill the remaining vertical space in the right column. The issue arises when setting the he ...

Problems encountered while utilizing PHP MVC with AJAX and JSON for deleting multiple records

A table listing records from the database with checkboxes containing associated ID values is displayed. <label class="m-checkbox"> <input type="checkbox" name="order_id[]" value="<?php echo sanitize($failed->order_id); ?>"> <span ...

A JavaScript pop-up box with two windows

Struggling to create two separate dialog boxes using this code. The issue is that when I add the code for the second dialog box, it only appears if the first one does too. Here's the code for the first dialog: function showPopUp(el) { var ...

Automatically send users to the login page upon page load if they are not authenticated using Nuxt and Firebase

I'm currently facing an issue with setting up navigation guards in my Nuxt application. The goal is to redirect users to the login screen if they are not authenticated using Firebase Authentication. While the router middleware successfully redirects u ...

Finding every instance of a specific day within a month

I am in need of a function that can provide me with all the occurrences of a specific day within the current month. I have the first and last day of the month, as well as the length of the month. While I have come across functions that offer the next occ ...