Toggle between images in Vue.js when an image is clicked

Hey there, I'm pretty new to Vue and could use some assistance with implementing a certain logic.

I have a JSON file that contains information about polaroids I've taken, such as their IDs, names, image names, and descriptions. Here's a snippet:

[
{
    "id": "PRD1",
    "image": "polaroid_1.jpeg",
    "name": "Christmas - 2020",
    "description": "blah blah blah"
},

{
    "id": "PRD2",
    "image": "polaroid_2.jpeg",
    "name": "Lost Love - 2021",
    "description": "Memories of a relationship that never was."
},
...    
]

I have a component in which I use a v-for loop to render these images. Here's the full HTML code:

<template>
<div class="images-wrapper">
    <div class="images" v-for="polaroid in polaroids" :key="polaroid">
        <img class="polaroid-image" :src="getImgUrl(polaroid.image)"/>
        <div class="information-wrapper"> 
            <div class="polaroid-title">
                {{ polaroid.name }}
            </div>
            <div class="polaroid-description">
                {{ polaroid.description }}
            </div>
        </div>
    </div>
</div>

The images are displayed perfectly in a grid within my Vue app. However, I'm unsure how to implement the logic that allows for clicking on an image to replace it with another image from the assets folder (e.g., polaroid_0.jpeg), and display the name and description of the clicked image.

Any suggestions on how to achieve this?

EDIT - Clarification

@FayçalBorsali Apologies for any confusion. To clarify, I want to be able to click on an image in the grid and have it switch to a different image, while also showing additional text (name and description). If I click the image again, it should revert back to the original image. Is it possible to have multiple selected images at once? For example, clicking on two different images to replace them with another image, while keeping the third image unchanged.

Answer №1

It seems like you're looking to implement a toggle functionality for displaying images using a boolean property in each polaroid object. You can achieve this by using a combination of v-if and v-else directives in your template. Additionally, you can use a click event listener to switch the boolean value back and forth. The display of the information-wrapper can also be linked to the same boolean property to show/hide the information accordingly.

<template>
<div class="images-wrapper">
    <div class="images" v-for="polaroid in polaroids" :key="polaroid">
        <img v-if="polaroid.show" @click="polaroid.show = false" class="polaroid-image" :src="getImgUrl(polaroid.image)"/>
        <img v-else @click="polaroid.show = true" class="polaroid-image" :src="getImgUrl('polaroid_0.jpeg')"/>
        <div v-if="!polaroid.show" class="information-wrapper"> 
            <div class="polaroid-title">
                {{ polaroid.name }}
            </div>
            <div class="polaroid-description">
                {{ polaroid.description }}
            </div>
        </div>
    </div>
</div>

Here is an example of a new boolean property added to each polaroid object:

{
    "id": "PRD1",
    "image": "polaroid_1.jpeg",
    "name": "Natale - 2020",
    "description": "blah blah blah",
    "show": true
}

Answer №2

If you're looking to achieve your desired outcome, there are several methods that could work, but I recommend the following:

  1. Keep track of whether an image has been clicked or not (you could do this by adding a boolean field to each polaroid and toggling it whenever an image is clicked)

  2. Make sure your :src is dynamic, which can be accomplished by either modifying the getImgUrl() function or by adding another field specifically for the selected image

For instance, your polaroids data could look like this:

[
{
    "id": "PRD1",
    "image": "polaroid_1.jpeg",
    "name": "Natale - 2020",
    "description": "blah blah blah",
    "show" : false,
    "clickedImage" : "polaroid_1.jpeg"
},

{
    "id": "PRD2",
    "image": "polaroid_2.jpeg",
    "name": "A love that never was - 2021",
    "description": "Before the first ever heartbreak of my life (the worst so far).",
    "show" : false,
    "clickedImage" : "polaroid_1.jpeg"
},
...    
]

Your template structure might look like this:

<template>
<div class="images-wrapper">
    <div class="images" v-for="polaroid in polaroids" :key="polaroid" @click="toggleImg(polaroid.id)">
        <img class="polaroid-image" :src="getImgUrl(polaroid)"/>
        <div class="information-wrapper"> 
            <div class="polaroid-title">
                {{ polaroid.name }}
            </div>
            <div class="polaroid-description">
                {{ polaroid.description }}
            </div>
        </div>
    </div>
</div>

And in your JavaScript code:

function getImgUrl(polaroid) {
  cont img = polaroid.show ? polaroid.clickedImg : polaroid.img;
  // Your current code
} 

These examples demonstrate the general approach outlined in my first two suggestions

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

Complications arising from IE when using strict doctype with CSS and jQuery

Here's the code I'm using for a sliding caption effect on my gallery site: I specifically implemented the last effect which is the Caption Sliding (Partially Hidden to Visible). $('.boxgrid.caption').hover(function(){ $(".cover", th ...

Seeking help with h2 headings, nested hyperlinks, and clickable images

Attempting to tackle a homework question today. This is the task at hand.... List a variety of foods in the following categories: Sandwiches, Drinks, Desserts. Use h2 tags to create these categories. Under each category, create a nested list that inc ...

What is the best way to centrally align a Card while keeping the text left-aligned?

New to coding and need some guidance. I'm attempting to create a card that is not the full width of the window. I have specified a cardStyle as shown below. cardStyle:{ width: '95vw' align? : 'center?' textAlign? : &a ...

Transform a row into a clickable element

I am currently working on a social media platform where users can search for venues stored in the database. In my search.php file, I have implemented a text box that dynamically loads venue names from the database into a venuesearch div as the user types. ...

The information returned to the callback function in Angular comes back null

In my Node.js application, I have set up an endpoint like this: usersRoute.get('/get', function(req, res) { //If no date was passed in - just use today's date var date = req.query.date || dateFormat(new Date(), 'yyyy-mm-dd&ap ...

Using VUE-JS to implement checkbox functionality with v-model

Click here for the image Greetings All, I am new to VUE.JS and seeking assistance. I have checkboxes for MODULES and FUNCTIONS My goal is to add functions for each module that I have. Below is a snippet of my code: <label> Modules:</label> ...

Receiving time slots on a bootstrap schedule

I recently developed a calendar using Bootstrap that allows users to select a start date and automatically sets the end date within a 7-day range from the chosen start date. However, I am facing a challenge in enabling users to also pick minutes along with ...

Mongoose documents are set to automatically be deleted after a duration of one month

My goal is to retain a particular document for one month after the client-user deletes it. To achieve this, I have decided to simulate a delete action and display data in the browser. Sample schema: const product = new mongoose.Schema({ --- trash : { ty ...

What is the best way to use SQL and Flask to automatically fill out a form based on a selection made from a

Looking for assistance with populating an HTML form by selecting a company from a dropdown menu. The desired result is similar to the example found here, using SQL and Flask. I'm unsure of how to retrieve the selected value from the <option> ta ...

Stylesheet failing to respond to CSS Media queries

I have looked at other questions with similar issues and it appears that what's missing in their code is: <meta name="viewport" content="width=device-width, initial-scale=1"> However, I already have this code implemented but still facing probl ...

Retrieve the initial 100 links using XPath and PHP

I wrote the following code to extract href's (links) from a web resource that contains more than 1000 links: $dom = new DOMDocument(); @$dom->loadHTMLFile('https://www.domain.me/'); $xpath = new DOMXPath($dom); $entries = $xpath->quer ...

Is there a way to insert copied links onto separate lines?

I have a list of links to Google search results. I have a checker that allows me to mark the links and copy them. My code is functioning properly, but I want each link to appear on a new line. ... Can someone please help me? I've attempted to add "< ...

How can jQuery be used to adjust the width and height of an iframe?

After researching a solution on a website, I attempted to implement it but encountered issues. It seems like there may be another script dictating the styling, so I need to add some code directly to the page to override it. This is what I tried: <scri ...

Is there a way to simulate a middle mouse click using Selenium and JavaScript?

I am looking to simulate a middle button mouse click on a text URL within a webpage using Selenium code in JavaScript so that it opens in a new tab. Here's an example: await driver.get("https://google.com"); // This is the xpath for the &a ...

Having trouble with NVM not working correctly in Ubuntu 21.04 Terminal?

Lately, I've been facing challenges with updating my Node.js version, and one method I tried was using node version manager. After downloading the install_nvm.sh file with the command curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/insta ...

Difficulty paginating jqgrid when using an array as the data source

Encountering an issue with pagination in jqgrid while working with array data containing 18 records. Even after specifying pagination:true, pager:jQuery('#pager1'), the records are not displaying in pages. Can anyone assist me in implementing pag ...

Surround the image with horizontal links on each side

I am attempting to design a horizontal unordered list with an image positioned in the center of it. I am facing the challenge of not being able to insert the image directly within the unordered list. Is there a way to align the image in the center while ha ...

What is the best way to make img-fluid function properly within Bootstrap Carousel?

I've been struggling to make my carousel images responsive by using the img-fluid tag, but I haven't had any success. I've attempted using !important and display: block, but nothing seems to work. I'm not sure what's causing the is ...

Steps for integrating a Facebook Messenger chatbot with a MongoDB database in order to submit requests and retrieve responses through conversations with the bot

I am currently working on integrating my Facebook Messenger chatbot with a MongoDB database. The chatbot I have created is a simple questionnaire chatbot that takes text inputs and displays buttons with options. When a user clicks on a button, it should ...

Exploring the importance of defining a JSONP callback function

I am relatively new to JavaScript and struggling with an issue in my code. My code includes an Ajax request to a server, and I receive a response from it. Due to the cross-domain nature of the request, I am utilizing JSONP. $.ajax({ url: "***", c ...