Activate the function within the same class only for the selected item

Hello there, I'm struggling to grasp how to make this particular functionality work.

Basically, I have 8 divs, each containing an image used as a button with the same class (tm-img), and hidden divs with additional information. My goal is to initially display only the images and when a user clicks on one of them, only the hidden div associated with that specific image should be shown. Unfortunately, at the moment, clicking on any image reveals all hidden divs instead of just the one clicked on.

<div class="tm-full-container">
                <div class="team-member card-container blue-card">
                    <img class='tm-img' onclick='run()' src="/team_1.png" alt="">
                    <h5 class="tm-title">Chef</h6>
                
                <div class="tm-info">
                    <p class="tm-name">Rick Jones</p>
                    <p class="tm-position">Chef</p>
                </div>

                </div>

                <div class="tm-full-info">
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at 
                        ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia 
                        tempora temporibus perspiciatis? Assumenda?</p>
                </div>
            </div>

<script>
     function run(){
      
      $('.tm-info').toggle();
      $('.tm-full-info').toggle();
      $('.tm-title').toggle();
    
     }</script>

The remaining 7 divs are identical, featuring different images but the same name (Rick).

Thank you for your help!

Check out this example

Answer №1

When considering the following code snippet:

$(function() {
  function displayFullInformation(event) {
    var target = $(event.target);
    var container = target.closest(".tm-full-container");
    $('.tm-info, .tm-full-info, .tm-title', contaner).toggle();
  }

  $(".tm-img").click(displayFullInformation);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tm-full-container">
  <div class="team-member card-container blue-card">
    <img class='tm-img' src="https://dummyimage.com/100x150/000/fff.png" alt="">
    <h5 class="tm-title">Chef</h6>
      <div class="tm-info">
        <p class="tm-name">Rick Jones</p>
        <p class="tm-position">Chef</p>
      </div>
  </div>
  <div class="tm-full-info">
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia tempora temporibus perspiciatis? Assumenda?</p>
  </div>
</div>

The key is to ensure you are using the right selector and context.

$('.tm-info, .tm-full-info, .tm-title', container).toggle();

This could also be expressed as:

container.find('.tm-info, .tm-full-info, .tm-title').toggle();

Answer №2

To achieve this, utilize the keyword "this":

.tm-info, .tm-full-info, .tm-title {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tm-full-container">
  <div class="team-member card-container blue-card">
      <img class='tm-img' src="https://via.placeholder.com/150" alt="">
      <h5 class="tm-title">Chef</h6>

  <div class="tm-info">
      <p class="tm-name">Rick Jones</p>
      <p class="tm-position">Chef</p>
  </div>

  </div>

  <div class="tm-full-info">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at 
          ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia 
          tempora temporibus perspiciatis? Assumenda?</p>
  </div>
 </div>
 
<div class="tm-full-container">
  <div class="team-member card-container blue-card">
      <img class='tm-img' src="https://via.placeholder.com/150" alt="">
      <h5 class="tm-title">Chef</h6>

  <div class="tm-info">
      <p class="tm-name">Rick Jones</p>
      <p class="tm-position">Chef</p>
  </div>

  </div>

  <div class="tm-full-info">
      <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at 
          ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia 
          tempora temporibus perspiciatis? Assumenda?</p>
  </div>
</div>

<script>
   $('.tm-img').click(function(){
    $(this).parent().parent().find('.tm-info').toggle();
    $(this).parent().parent().closest('.tm-full-info').toggle();
    $(this).parent().parent().closest('.tm-title').toggle();
  });
</script>

Answer №3

Here's a handy snippet to achieve this functionality. Utilize the this keyword to ensure only the clicked element is affected.

Alternatively, you can employ a for loop to iterate through all tags and toggle the clicked event.

function toggleInfo(show) {
  var showInfo = show.querySelector(".tm-tag-Info");
  showInfo.classList.toggle("tm-tag-Info-Show")
}
.tm-tag-Info {
  display: none
}

.tm-tag-Info-Show {
  display: block
}

.tm-tag {
  border: 2px solid red;
  margin: 10px;
  padding: 10px;
}

.imageFun {
  width: 100px;
  height: 100px
}
<div class="tm-tag" onclick="toggleInfo(this)">
  <h4 class="tm-tag-Hed">CV for BV</h4>
  <span class="tm-tag-Info"><img alt="imageFun" src="https://www.hdnicewallpapers.com/Walls/Big/Rainbow/Rainbow_on_Mountain_HD_Image.jpg" class="imageFun"><br>Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia tempora temporibus perspiciatis? Assumenda?</span>
</div>

<div class="tm-tag" onclick="toggleInfo(this)">
  <h4 class="tm-tag-Hed">CV for BV</h4>
  <span class="tm-tag-Info"><img alt="imageFun" src="https://www.hdnicewallpapers.com/Walls/Big/Rainbow/Rainbow_on_Mountain_HD_Image.jpg" class="imageFun"><br>Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia tempora temporibus perspiciatis? Assumenda?</span>
</div>

<div class="tm-tag" onclick="toggleInfo(this)">
  <h4 class="tm-tag-Hed">CV for BV</h4>
  <span class="tm-tag-Info"><img alt="imageFun" src="https://www.hdnicewallpapers.com/Walls/Big/Rainbow/Rainbow_on_Mountain_HD_Image.jpg" class="imageFun"><br>Lorem ipsum dolor sit amet consectetur adipisicing elit. Error magnam aliquam similique at ipsam accusamus sed enim, in non ipsa excepturi reprehenderit fugit velit libero mollitia tempora temporibus perspiciatis? Assumenda?</span>
</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

Tips on positioning only one list item on your Bootstrap navbar to the right

I am currently learning to code with HTML and am attempting to create a navigation bar with some list items on the right side and some on the left. Although I'm using Bootstrap, I am unable to figure out how to move only the 'contact' item t ...

How can you identify changes in localstorage and then trigger the activation of a new boot file or reallocate a value using Vue.js or JavaScript?

When users log in, they have the option to choose from 3 domains: dev, demo, and sandbox. The configuration for these domains is set in the Boot.js file using Axios. The boot file is triggered prior to the firing of the Vue instance. Below is the content o ...

Guide to implementing if statements within a map function in JavaScript/Vue.js

Currently, I am developing a small application using Vuejs. In this application, I receive response data and then map it to a variable. However, there are some elements with empty arrays in the data. So, during mapping, I need to check a condition and ma ...

Is there a way to verify the presence of "li" elements before adding them?

I'm a jQuery beginner and I've been working on adding new <li> items to a list, but only if the item does not already exist. For instance: <ul id="myList"> <li>Item 1</li> <li>Item 2</li> </ul&g ...

Discover the identity of an element through the value of another element

Looking for a way to retrieve the id value based on the input value in this HTML code. For instance, I need to identify the id value associated with the input value of number2 - which is unknown2. How can this be achieved using jQuery? <th id="unknow ...

Tips for maintaining a persistent login session in React Native with Firebase forever

I've been grappling with this issue for a few days now. Essentially, my aim is to have Firebase remember the user so they remain logged in after logging in once. The first block of code is the App component (I've omitted some of the irrelevant co ...

Encountering the error "Unable to access the 'pickAlgorithm' property of null" in a ReactJS context

Encountering an issue during npm install process. npm install -g netlify-cli The error message displayed is: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a2a5b0a5a2b5fcb2bdb8b4bfa591e1ffe5ffe6"> ...

Using a Javascript hyperlink to trigger a POST request in Python

I am currently developing a web scraping and automation tool that requires the use of POST requests to submit form data. The final action involves using the following link: <a id="linkSaveDestination" href='javascript:WebForm_DoPostBackWithOptions ...

A gap only appears in the drop-down navigation when the page is scrolled

After finally completing my first website, I encountered a frustrating issue. When scrolling down the page, a gap appears in the navigation bar, making it impossible to access the dropdown menus. I've been struggling to fix this problem on my own. Any ...

What is the process for simulating form submission using jQuery?

I am working on an ASP.NET web page with a form that includes a submit button. I have integrated validation logic into the client-side click event of the button. Now, I want to be able to submit this form through my jQuery validation logic. Can someone p ...

What causes the indexOf method to return -1 even when the values are present in the array?

Could someone explain why the indexOf() method returns -1 even though the values are present in the array? The includes() function also returns false for me. I feel like I must be missing something or forgetting a crucial detail. Any insights on why the ...

Guide to sending a post request with parameters in nuxt.js

I am trying to fetch data using the fetch method in Nuxt/Axios to send a post request and retrieve specific category information: async fetch() { const res = await this.$axios.post( `https://example.com/art-admin/public/api/get_single_cat_data_an ...

There was a dependency resolution error encountered when resolving the following: [email protected] 12:15:56 AM: npm ERR! Discovered: [email protected] . The Netlify deploy log is provided below for reference

5:27:42 PM: Installing npm packages using npm version 8.19.3 5:27:44 PM: npm ERR! code ERESOLVE 5:27:44 PM: npm ERR! ERESOLVE could not resolve 5:27:44 PM: npm ERR! 5:27:44 PM: npm ERR! While resolving: [email protected] 5:27:44 PM: npm ERR! Foun ...

Adding hue to the portion of text following a JavaScript split() operation

I need assistance in printing the text entered in a textarea with different colors. I am separating the string using the split() method, which works fine. However, I now want to print the substrings in the textarea with colors. How can this be achieved? & ...

What is the best way to incorporate a fresh array into the existing array element stored in local storage?

I stored a group of users in the local storage: let btnSignUp = document.getElementById("btnSignUp"); btnSignUp.addEventListener('click', (e) => { let existingUsers = JSON.parse(localStorage.getItem("allUsers")); if (existingUsers == null ...

Adding JavaScript files to a project in Ionic2 with Angular2 integration

I'm looking to incorporate jQuery into my Ionic2 app, which requires loading several JavaScript files: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <script type="text/j ...

HTML stubbornly resists incorporating Javascript [UIWebView]

Currently, I am facing an issue while trying to animate a color property using jQuery 1.7.1 and the jquery color plugin downloaded from this link. I have ensured that all necessary files are included and part of the build target. Here is a simplified versi ...

Issue with Angular 9 Json pipe not showing decimal values

My JSON data looks like this: this.data = {"eoiStatistics": [ { "dateRange": { "explicitStartDate": "1997-01-01T00:00:00", "explicitEndDate": "2019-07-01T00:00:00" }, "outstandingApplicationCount": 0.0, "pendingApplicationCount": 24.0, " ...

Choose a division of an element within an embedded frame

Two different pages on the same website, Home.html and Page2.html. Home.html contains the following code: <html> <iframe id="one" src="page2.html" style="display:none"></iframe> <div id="container"> <h1& ...

The issue arises when trying to use jQuery on multiple elements with the same class

Recently, I came across a jQuery script for my mobile menu that changes the class on click event. jQuery("#slide-out-open").click(function() { if( jQuery( this ).hasClass( "slide-out-open" ) ) { jQuery('#wrapper').css({overflow:"hidd ...