I need to swap out a pair of images simultaneously

Is it possible to use JavaScript to change the images in imageBox1 and imageBox2 simultaneously when clicking a button? For example, if I click "hello", I want image1-1 and image2-1 to be displayed together. And if I click "world", then image1-2 and image2-2 should display at the same time.

    <div class = "Button">
        <button type="button">hello</button>
        <button type="button">world</button>
    </div>

    <div class = "imageBox1">
        <img src="image1-1.jpg">
        <img src="image1-2.jpg">
    </div>

    <div class = "imageBox2>
        <img src="image2-1.jpg">
        <img src="image2-2.jpg">
    </div>

Answer №1

To create a dynamic button event listener that shows corresponding images in each div, you can loop through the buttons and images. When a button is clicked, only the image with the same index as the button will be displayed.

const divs = document.querySelectorAll('.image');

const buttons = document.querySelectorAll('button')

buttons.forEach((button, index) => {
  button.addEventListener('click', function() {
    divs.forEach((div) => {
      [...div.children].forEach((img, imgIndex) => {
        img.style.display = (index === imgIndex) ? "block" : "none";
      });
    });
  });
});
img {
  display: none;
}
<div class="Button">
  <button type="button">hello</button>
  <button type="button">world</button>
</div>

<div class="imageBox1 image">
  <img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1">
  <!-- image1-1.jpg -->
  <img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=96">
  <!-- image1-2.jpg -->
</div>

<div class="imageBox2 image">
  <img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=96">
  <!-- image2-1.jpg -->
  <img src="https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1">
  <!-- image2-2.jpg -->
</div>

Answer №2

If you're looking to toggle specific images based on user button clicks, JavaScript is the way to go!

Check out this simple example tailored for beginners:

// Create variables for better code readability

const helloButton = document.getElementById("hello-button")
const worldButton = document.getElementById("world-button")
const image1 = document.getElementById("image1")
const image2 = document.getElementById("image2")
const image3 = document.getElementById("image3")
const image4 = document.getElementById("image4")

// When "hello" button is clicked, call handleHelloClick function

helloButton.addEventListener("click", handleHelloClick);

// When "world" button is clicked, call handleWorldClick function

worldButton.addEventListener("click", handleWorldClick);

// Function to show/hide images when "hello" button is clicked

function handleHelloClick() {
  image1.style.display = "none";
  image2.style.display = "block";
  image3.style.display = "block";
  image4.style.display = "none";
}

// Function to show/hide images when "world" button is clicked

function handleWorldClick() {
  image1.style.display = "block";
  image2.style.display = "none";
  image3.style.display = "none";
  image4.style.display = "block";
}
<div class="buttons">
  <button id="hello-button" type="button">hello</button>
  <button id="world-button" type="button">world</button>
</div>

<div class="imageBox1">
  <img id="image1" src="https://randomuser.me/api/portraits/women/75.jpg">
  <img id="image2" src="https://randomuser.me/api/portraits/men/76.jpg">
</div>

<div class="imageBox2">
  <img id="image3" src="https://randomuser.me/api/portraits/women/78.jpg">
  <img id="image4" src="https://randomuser.me/api/portraits/men/80.jpg">
</div>

Answer №3

To begin, conceal them using CSS and then reveal them upon clicking with JavaScript.

const hello = document.getElementById("hello")
const world = document.getElementById("world")


hello.onclick= () => {
document.querySelectorAll(".first").forEach(el=> el.style.display = "block")
}

world.onclick= () => {
document.querySelectorAll(".second").forEach(el=> el.style.display = "block")
}
.first, .second {
display : none
}
 <div class = "Button">
        <button id="hello" type="button">hello</button>
        <button id="world" type="button">world</button>
    </div>

    <div class = "imageBox1">
        <img class="first" src="https://dummyimage.com/200x100/000/fff&text=first">
        <img class="second" src="https://dummyimage.com/200x100/000/fff&text=second">
    </div>

    <div class = "imageBox2">
        <img class="first" src="https://dummyimage.com/200x100/000/fff&text=first">
        <img class="second" src="https://dummyimage.com/200x100/000/fff&text=second">
    </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

Error in refreshing JWPlayer page: Plugin loading failure - File not located

I'm implementing JWPlayer on my Localhost environment. Here's the code snippet I'm using: <div id="Player">loading...</div> <script type="text/javascript"> jwplayer("Player").setup({ file: "<?php echo $video[' ...

Creating an associative array in javascript: A step-by-step guide

I require an array to be structured in the following manner: {"3": {"label":"All i want for christmas", "song":"Alliw_1405399165.mp3", "name":"All i want for christmas"}, "4": {"label":"Call your girlfriend robyn clip", "song":"Gang ...

Tips for programmatically choosing images from a Google Photos collection?

Currently, I am attempting to use code in the console to automatically choose a photo from a Google Photos Album while browsing. I've tried this method so far: const photo = document.getElementsByClassName('p137Zd')[0].parentElement photo. ...

Iterating over ng-repeat, the initial item with a distinct directive

I have this code snippet: <div ng-repeat="i in placeholders" square class="set-holder {{i.class}}" droppable="{{i.type}}"></div> How can I ensure that the first item has the directive bigsquare, while the rest have just square? I attempted: ...

What is the method for incorporating an async middleware into a router route?

I am currently setting up routes for an express router in my project. I have a validator that deals with promises, requiring me to use await in the code. Here is how it looks: constructor() { this.router = express.Router(); this.router.use(express. ...

Express.js: Communicating with internal microservices

I'm still learning about node.js, express.js and REST APIs. Here's the situation I'm facing: I have a requirement to retrieve user information from my database (using mongoDB) in various scenarios. What would be the recommended approach i ...

What steps are involved in generating a scene dynamically with A-Frame?

Looking to transition from declarative coding in js and html to a programmatic approach with Aframe? You might be wondering if it's possible to modify your scene dynamically, here is an example of what you're trying to achieve: <!DOCTYPE html ...

AngularJS: Ensuring Controller Functions are Executed Post AJAX Call Completion via Service

Here's the code snippet I have in my service. this.loginUser = function(checkUser) { Parse.User.logIn(checkUser.username, checkUser.password, { success: function(user) { $rootScope.$apply(function (){ $rootScop ...

What is the method for showcasing a specific value using a filter?

In my app, I have the following data: birthdayGreetings:Array<any> = [ { name: 'John', date: new Date(1994, 3, 19), greeting: 'Happy Birthday, John! Good luck!', displayName: false } ]; I ...

Modify the parameters of the apps.facebook.com URL using the Facebook API

Is there a way to modify the parameters in the URL for apps.facebook.com using JavaScript? For instance, if a user chooses a photo, can we change the URL to apps.facebook.com/myapp/?photo_id=23234? This would allow the user to easily share the link with a ...

Guide on sending a message to a specific channel using Discord.js version 13 with TypeScript

After recently diving into TypeScript and seeing that Discord.js has made the move to v13, I have encountered an issue with sending messages to a specific channel using a Channel ID. Below is the code snippet I am currently using: // Define Channel ID cons ...

Ways to convert a JavaScript object into restful GET parameters in order to append them to the end of an API URL

Suppose we have a JSON object like this: { name: 'Tony', age: '20', birthday: '20180101', } What is the best way to convert it into parameters that can be appended at the end of a RESTful GET API URL, such as the ...

Upcoming topics - The Challenge of Staying Hydrated at Basecamp One

I have implemented a themes package for dark mode and light mode in my project. Despite doing the installation correctly as per the repository instructions, I am encountering an issue. My expected behavior for the project is: The webpage should initially ...

How can I ensure that my script reruns when the window is resized?

Clearly, the question is quite straightforward... I have a script that is drawing graphics across the window. Currently, when I resize the window (e.g., make it full screen), the script only responds to the original size of the window. It should refresh a ...

Translate3d increases the whitespace towards the end of the page

After implementing a smooth scroll on my webpage using transform translate3d, I encountered an issue. The translate3d function seems to be adding extra space at the end of the document, as illustrated here: https://codepen.io/anon/pen/WEpLGE I suspect the ...

The ng-repeat directive is causing issues with the functionality of the Angular carousal

I am currently trying to create an Angular carousel for displaying image slides that are coming from an array. However, I am facing issues as it is not functioning as a slider. Does anyone have a solution to fix this problem? //HTML <div id="myCarous ...

ReactJs: The input value remains stagnant due to the utilization of Array.map

Here is the content within the table body: <tbody> {this.state.composantInformation.map(composantInfo => { return ( <tr key={composantInfo.id.toString()}> <td>{composantInfo.nom_composant}</td> <td& ...

Utilize the Webstorm debugger in conjunction with node.js for seamless debugging

Several weeks ago, I attempted to get the webstorm debugger up and running, but unfortunately, it didn't work. Now, I'm giving it another shot, but I'm faced with the same outcome. I am following the instructions outlined here: http://www.j ...

Expanding the `Odds` data points found in a JSON array by calculating their product

When I receive a JSON array from a URL, it looks like this: {"soccerodds2017":[ {"Selections":"Chelsea","Odds":"1.44"}, {"Selections":"Wolverhampton","Odds":"2.33"}, {"Selections":"Walsall","Odds":"2.70"} ]} I want to multiply the odds by 10. ...

Unable to show <LI> elements

I'm having trouble adding LI items to the #historial <UL> tag. Whenever the for loop is inside the function, the list displays with some elements duplicated. I believe the for loop should remain outside of the function. Could someone please he ...