Instructions for swapping images by triggering a .on click event with four buttons

Hi everyone, I could really use your assistance with this issue. Let me explain the situation. I have 4 buttons that are meant to trigger different images. When a button is clicked, it should become active (I think I have this part figured out, but let me know if there's a better approach).

SCENARIO:
If I click on button 2, "image2" should appear with the class "active".
Then, when I click on button 3, "image2" should fade out (lose its "active" class) and "image3" should gain the "active" class.

Here are the 4 buttons:

<div id="button">
  <div class="trigger button-1" data-target="0"></div>
  <div class="trigger button-2" data-target="1"></div>
  <div class="trigger button-3" data-target="2"></div>
  <div class="trigger button-4" data-target="3"></div>
</div>

And here is how the images section is structured:

<div id="images-container">
  <img src="image-1" class="image1">
  <img src="image-2" class="image2">
  <img src="image-3" class="image3">
  <img src="image-4" class="image4">
</div>

I was wondering if there's a way to retrieve the images in jQuery using the data element?

Here is my current jQuery code:

var img = $('#images-container img'),
    trigger = $('.trigger');

// When a trigger is clicked, make it active and deactivate others
trigger.on('click', function(){
    $(this).addClass('active');
    $(this).siblings().removeClass('active');

    // Make the image with the selected ID active
    var a = $(this).data('target');
    $('#image-container').find('img').eq(a).addClass('active');

            // This is where I need assistance!

I realize this may be simple for some, but I'm not a jQuery expert. Any solutions would be greatly appreciated, and +1 for the best solution!

Answer №1

Include a data attribute in your HTML that corresponds to the image class and add a class...

Give this a try

HTML

<div class="trigger button-1" data-target="0" data-imageclass="image1"></div>
<div class="trigger button-2" data-target="1"  data-imageclass="image2"></div>

JQUERY

 var img = $('#images-container img'),
 trigger = $('.trigger');

 // When clicked, make this active and deactivate others
trigger.on('click', function(){
  $(this).addClass('active');
  $(this).siblings().removeClass('active');

  $('#images-container img').removeClass('active');
  $('.'+$(this).data('imageclass')).addClass('active');
}); 

Check out the fiddle here

If you're not using data-target in your code, consider using it instead of creating a new data attribute.

$('.'+$(this).data('target')).addClass('active');

Answer №2

If your scenario is straightforward, using tag position indexes should suffice. Typically, if the trigger buttons and target images have the same number, this method should work since they will have the same position indexes.

Consider the following example:

var img = $('#images-container').find('img'),
    trigger = $('.trigger');

$('#button').on('click', '.trigger', function(e) {
    var self = $(this), // current trigger element
        selfIndex = self.index(); // index of the current trigger element

    img.removeClass('active'); // remove 'active' class from all images
    img.eq(selfIndex).addClass('active'); // add 'active' class to the corresponding image

    trigger.removeClass('active'); // remove 'active' class from all triggers
    self.addClass('active'); // add 'active' class to the current trigger

    e.preventDefault();

});

However, if you prefer to use data attributes, modify your buttons' data attribute values as follows:

<div id="button">
  <div class="trigger button-1" data-target="image1"></div>
  <div class="trigger button-2" data-target="image2"></div>
  <div class="trigger button-3" data-target="image3"></div>
  <div class="trigger button-4" data-target="image4"></div>
</div>

Then in your JS/jQuery code, implement the following:

var img = $('#images-container').find('img'),
    trigger = $('.trigger');

$('#button').on('click', '.trigger', function(e) {
    var self = $(this);

    img.removeClass('active'); // remove 'active' class from all images
    img.filter('.' + self.data('target')).addClass('active'); // add 'active' class to the targeted image

    trigger.removeClass('active'); // remove 'active' class from all triggers
    self.addClass('active'); // add 'active' class to the current trigger

    e.preventDefault();

});

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

Is the 404 error a result of the ajax code?

I'm currently working on a form that utilizes AJAX to validate and interconnect various form elements. Below is a simplified version of my code: <?php if( isset( $_POST['create_transaction'] ) ) { // do something } ?> <div> ...

HTML and JavaScript - Facing issues rendering HTML content during the conversion process from Markdown format

In this particular scenario, my goal is to transform the content inside #fileDisplayArea into markdown format. However, I am encountering an issue where the HTML code within the div element is not being rendered. <div id="fileDisplayArea"># Title ...

Error: Unable to iterate through songs array due to songs.map not being recognized

Hello, I'm currently learning React and encountering the same error every time I run this code. Can someone please help me identify what's wrong with it? import React, { Component } from 'react' import '../Search.css' import ...

Troubleshooting import issues when starting with Webpack

Starting out with Webpack and already facing an issue. I've followed the documentation by creating an app/index.js file, as well as an index.html file (with HTML and CSS copied from the docs). Ran necessary CLI commands including generating a dist/bun ...

When using the parseFloat function with a regular expression input, it results

My goal is to adjust float values within a string by a specific amount. Here is my current approach: var string = '<path d="M219.6,-71.4C249,19.1,212.7,130.9,135.7,186.8C58.8,242.7,-58.8,242.7,-135.7,186.8C-212.7,130.9,-249,19.1,-219.6,-71.4C-19 ...

The functionality of event binding is unable to function properly on elements that are created dynamically

I am currently developing a shopping cart feature where I store product information in session variables. I have implemented an AJAX functionality to add products to the cart dynamically on the HTML page, which works fine. However, I am facing issues whe ...

Is there a way for AJAX to dynamically insert new rows into a table?

I am seeking assistance in dynamically adding rows to an HTML table using AJAX whenever additional records are retrieved from a database query. My workflow involves utilizing Python Flask and Pandas to generate a dataframe containing information about node ...

What is the best way to submit updated data from an Angular form?

Currently, I have a situation where multiple forms are connected to a backend service for storing data. My query is whether there exists a typical angular method to identify which properties of the model have been altered and only send those in the POST r ...

Struggling to implement dynamic templates in an Angular directive

In the process of developing a small angular application that consists of 3 modes - QA, Production, and Sandbox. In the QA mode, there are multiple buttons for users to select values which then populate "myModel". The other two modes, Production and Sandbo ...

Click on the print icon in the modal window

I have been working on a receipt generator for a client. The client can add payment receipts using the "Add" button, and upon submission, they have the option to convert it to PDF or print it. However, there seems to be an issue with printing as the text f ...

Is it possible to simultaneously toggle buttons and submit a form?

I am currently working on a functionality that involves toggling the display of two buttons and submitting a form. Code toggleButtons() { var btn1 = document.getElementById("start"); var btn2 = document.getElementById("pause"); if (btn1.style. ...

Django project encountering issue with linking Css file

I need help linking a CSS file with my Django project. I've tried multiple methods, but I'm not seeing any changes reflected on the HTML page. As a newcomer to this, any assistance would be greatly appreciated. Below is my HTML code : {% extend ...

creating dynamic applications using ant framework

I'm having some challenges while trying to develop JS applications with Ant. I have a directory named src and each subdirectory inside it is considered a "mini-app". When I iterate through each subdirectory using subant, I'm struggling to get ...

I am facing an issue with the clearTimeout function in my JavaScript code. Can anyone help

I am encountering some issues with the clearTimeout() function. The setTimeout() function is working as expected, but I want it to stop running when I close my notification. I'm not sure what is causing the problem in my function. After closing the ...

Is there a way to eliminate the impact of Jquery Document Click Listeners on a React Element?

We are currently in the process of rewriting parts of our legacy web app using React incrementally. As a result, we are unable to completely eliminate various document listeners that are scattered throughout the code. The presence of these listeners on dif ...

the div's width isn't getting larger

Check out my code snippet: <script> var change = function(){ alert("sam"); for(var i; i >=200; i++){ var z = String(i); var x= document.getElementById("div1"); x.style.width = z; } }; </script> < ...

Styling WordPress twenty seventeen custom header with CSS tags

I have encountered a problem on my website where the custom header is causing issues on all pages except the home page. Specifically, in the custom header div element there is a style tag adding a margin-bottom of 82px. Despite searching through template p ...

Unveiling the secrets to retrieving JSON array objects in HTML with the help of Angular!

Looking to display a JSON file in HTML, but struggling with syntax for deeply nested objects. { "questions": [ { "question": "Qw1", "answers": [ { "answers": "An1", "value": 25 }, { ...

Firefox experiencing a line break issue when using html() event

Is it just me or does anyone else experience the issue of text breaking into two lines momentarily on Firefox when trying to change text on an element after another element is clicked? It works perfectly on Chrome, but I can't seem to figure out why i ...

A Bluebird promise was generated within a NodeJS handler function, however it was not properly returned from the function

Below is the nodejs code for an express middleware function: Middleware.is_authenticated = function(req, res, next) { if(req.system_session == undefined || req.system_session.login_status == false) return res.status(401).send({errors: true, error: &ap ...