simplified code - toggle section visibility

$(".link1").click(function(){
 $(".slide2, .slide3, .slide4, .slide5").css("opacity", 0.0);
$(".slide1").fadeTo("slow", 1.0);
  });
  $(".link2").click(function(){
 $(".slide1, .slide3, .slide4, .slide5").css("opacity", 0.0);
$(".slide2").fadeTo("slow", 1.0);
  });
  $(".link3").click(function(){
 $(".slide2, .slide1, .slide4, .slide5").css("opacity", 0.0);
$(".slide3").fadeTo("slow", 1.0);
  });
  $(".link4").click(function(){
 $(".slide2, .slide3, .slide1, .slide5").css("opacity", 0.0);
$(".slide4").fadeTo("slow", 1.0);
  });
  $(".link5").click(function(){
 $(".slide2, .slide3, .slide4, .slide1").css("opacity", 0.0);
$(".slide5").fadeTo("slow", 1.0);
  });
.slide1, .slide2, .slide3, .slide4, .slide5 {
  position: absolute;
  left: 0%;
  top: 0%;
  right: 0%;
  bottom: 0%;
  display: -webkit-box;
  display: -webkit-flex;
  display: -ms-flexbox;
  display: flex;
  margin: 0 auto;
  width: 50vw;
  height: 50vh;
  -webkit-box-pack: center;
  -webkit-justify-content: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -webkit-align-items: center;
  -ms-flex-align: center;
  align-items: center;
  background-color: #fff;
  opacity: 0;
}

.link1, .link2, .link3, .link4, .link5 {
  width: 100px;
  height: 100px;
  margin-right: 133px;
  margin-left: 2px;
  padding-left: 0px;
}
.thumbWrapper{
  position: absolute;
  left: 0%;
  top: 0%;
  right: 0%;
  bottom: 0%;
  padding-bottom: 0px;
  background-color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <div>
    <div class="thumbWrapper">
      <div><a href="#" class="link1"><img src="https://images.unsplash.com/photo-1578491133524-f33d9c7a7484?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w... 
    </div>
</p>

<p>I will have 40 different thumbs and 40 large images that are placed all on absolute with their opacity set to zero.
On thumb click, the image should fade in. I started some code for just 5 links but I feel like there must be a shorter way to do this for my 40 links... Any ideas?</p>

<p>Thank you!!!</p>

<p>I have written this so far:</p>

<p><div>
<div>
<pre class="lang-js"><code><script>
$(".link2").click(function(){
 $(".slide11, .slide1, .slide3, .slide44, .slide55, .slide66").css("opacity", 0.0);
$(".slide2").fadeTo("slow", 1.0);
  });
  $(".link1").click(function(){
 $(".slide2, .slide1, .slide3, .slide44, .slide55, .slide66").css("opacity", 0.0);
$(".slide11").fadeTo("slow", 1.0);
  });
  $(".link3").click(function(){
 $(".slide11, .slide1, .slide2, .slide44, .slide55, .slide66").css("opacity", 0.0);
$(".slide3").fadeTo("slow", 1.0);
  });
  $(".link4").click(function(){
 $(".slide11, .slide1, .slide3, .slide2, .slide55, .slide66").css("opacity", 0.0);
$(".slide44").fadeTo("slow", 1.0);
  });
  $(".link5").click(function(){
 $(".slide11, .slide1, .slide3, .slide44, .slide2, .slide66").css("opacity", 0.0);
$(".slide55").fadeTo("slow", 1.0);
  });
  </script>

Answer №1

To implement this functionality, you should add the click event listener to the parent element containing your links, for example:

<div id="thumbs-container">
    // place links with IDs like link1, link2 here
</div>

Make sure that your links and slides have consistent IDs and classes, respectively. For instance, #link4 corresponds to .slide4. Here's how you can accomplish this:

var LINK_PREFIX = "link";
var SLIDE_CLASS_PREFIX = ".slide";

var totalSlides = 40;
var slides = [];

for (var slideNum = 1; slideNum <= totalSlides;  slideNum++) {
    slides.push(SLIDE_CLASS_PREFIX + slideNum);
}

var container = document.getElementById("thumbs-container");

container.addEventListener('click', (event) => {
    var targetId = event.target.id;

    if (targetId.indexOf(LINK_PREFIX) === -1) return; // optional check: not clicked on any link
    var slideNum = targetId.replace(LINK_PREFIX, "");

    var slideToFadeIn = SLIDE_CLASS_PREFIX + slideNum;
    var slidesToHide = slides.filter(slide => slide !== slideToFadeIn);

    $(slidesToHide.join(", ")).css("opacity", 0.0);
    $(slideToFadeIn).fadeTo("slow", 1.0);
});

Answer №2

If you want to improve your approach, I recommend being more assertive in your coding style. Take a look at the example below, which provides two different perspectives on how to tackle the animation.

var element = document.getElementById('disp')
element.addEventListener('click', function(event) {
  document.querySelectorAll('.showOne div.active')
          .forEach( el => el.classList.remove('active'))
  event.target.classList.add('active')
})
.showOne div {
  opacity: 30%;
  transition: opacity 500ms;
}
.showOne div:hover {
  animation: anim-fade 1s ease;
  color: green;
}
.showOne div.active {
  color: red;
  opacity: 100%;
}

@keyframes anim-fade {
  0% {
    opacity: 30%;
  }
  100% {
    opacity: 100%;
  }
}
<div id="disp" class="showOne">
  <div> AAAA </div>
  <div> BBBB </div>
  <div> CCCC </div>
  <div> DDDD </div>
</div>

Answer №3

A single click event can be used to identify the parent element of the clicked item, determine its position among its siblings within the grandparent element, and then show the specific item while hiding the rest:

$(".thumbWrapper > div > a").click(function() {
    var parent = this.parentNode;
    $(".slide" + ([...parent.parentNode.children].indexOf(parent) + 1)).fadeTo("slow", 1.0).siblings().css("opacity", 0.0);
})

Answer №4

A different method to achieve the same result is outlined below:

// To demonstrate, let's create 40 images and add them to the DOM:
var i = 1;
while (i < 41) {
  var sliderEl = document.createElement("img"); 
  sliderEl.setAttribute('class','slider'); 
  sliderEl.setAttribute('src','https://via.placeholder.com/200x60.png?text=demoIMG'+i);
  sliderEl.addEventListener('click', showImg); // this will trigger on click
  document.body.appendChild(sliderEl); 
  ++i;
}

// The function below executes when an image is clicked:
function showImg() {
  var sliders = document.querySelectorAll('.slider');
  for (var i=0; i < sliders.length; i++) {
    sliders[i].removeAttribute('style');
  }
  this.setAttribute('style', 'position: fixed; top: calc(50vh - 100px); left: calc(50vw - 100px); transform: scale(2,2);');
};
.slider {display: block; border: 1px solid black; margin: 20px;}

This approach offers a faster way to configure and control elements. Happy coding!

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

Creating a self-chaining function in JavaScript: A guide

Currently, my goal is to create an Array.prototype function called union( array_to_union ), and then utilize it in the following manner: var a = [1,2,3]; a.union([2,3,4]).union([1,3,4]) ...... I am aiming for the outcome to be the union of these arrays. ...

Updating an individual item from an array of objects using ReactJS

I am facing an issue with my database's Opening Time table. Whenever I try to modify the opening time of one day, the opening time of other days gets deleted as well. Below is the code snippet I'm using to update my state data: async handleCha ...

Using AngularJS to send the $http response back to the calling object

Is there a way to pass the response value to the parent object, specifically the invoker of an http service call in AngularJS? I have a BaseModel that performs the GET request as shown below. The goal is for the basemodel object instance to hold the respon ...

Automatically save checked checkboxes in localStorage

In my PHP code, I have something similar to the following: if(isset($_POST['submit']){ $check = in_array($row['service_object_id'], $values) ? 'checked' : ''; } echo ...

Invalidating the express response object due to a TypeError issue

Currently, I am in the process of writing a test that utilizes sinon and sinon-express-mock to mock an incorrect request. The goal is to then call a validation function within my application and verify that it returns the expected response status code (400 ...

Sending JSON Data with Javascript Post Request

I've been attempting to send a JSON payload via a JavaScript script, but my webhooks don't seem to recognize the payload no matter what I try. Here is the code that I compiled from various online resources: let xhr = new XMLHttpRequest(); ...

When trying to create a MongoStore object, an error occurred because the property 'create' was not defined

I have exhausted all possible solutions I could find, but the issue remains unresolved. The error message is as follows: C:\Users\...............\server.js:35 store: MongoStore.create({ ^ TypeError: Cannot read property &a ...

How to use TypeScript to filter an array based on the values of another array

Suppose I have two arrays. The first one looks like this: names: [{ value: 'recordedData', desc: 'Data' } { value: 'recordedNumbers', desc: 'numbers' } { value: 'recordedNames', desc: 'name ...

What is the best way to retrieve a Promise from a store.dispatch within Redux-saga in order to wait for it to resolve before rendering in SSR?

I have been experimenting with React SSR using Redux and Redux-saga. While I have managed to get the Client Rendering to work, the server store does not seem to receive the data or wait for the data before rendering the HTML. server.js ...

Using `require(variable)` is not functional in next-js environment

I'm attempting to display an image using the next-optimised-images module. When I try to include images like this: <img src={require(c.logo)} alt={c.title} /> I encounter the following error: https://i.stack.imgur.com/Jtqh9.png However, when ...

The slide experiences overflow as it continuously slides up and down

Hey everyone, I've been working on creating a slider effect when a button is clicked. Details about a specific part appear in a designated div upon button click. However, I've encountered a bug where, if I click quickly on different slides, the c ...

The logo on my header is being covered by the menu due to the CSS code

Check out my website at bee-barcelona.herokuapp.com I'm facing an issue where the menu overlaps with the logo when I resize the browser or view the webpage on a tablet. I want to fix this using CSS. What changes do I need to make to ensure that the e ...

Adjusting Size Dynamically for Tooltips Based on Content Length

In my angular app using ng-bootstrap v4.2.1 on an older codebase, I have successfully created a tooltip with some very long sentences as content. I am trying to make the tooltip 800px wide, but when I set the width, only the first few words fill the space. ...

Rendering HTML or links sourced from encoded JSON data with JavaScript

After making an ajax call, I receive the following data: {"dataList":[{"date":"August 27, 2013","text":"<a href=\"http:\/\/www.example.com\/test.aif\" title=\"Click here to listen\" target=\"\">Click her ...

How about mixing up your backgrounds with an overlay effect for a unique look?

Hey there, I'm currently working on adding random backgrounds to my website through an overlay, but I've hit a roadblock when it comes to displaying them. Here is the code I'm working with: .css / .php #intro { background: ...

Utilizing Azure SDK to send an email

In my Node.js project, I am currently utilizing azure-graph: const MsRest = require('ms-rest-azure'); const credentials = await MsRest.loginWithServicePrincipalSecret(keys.appId, keys.pass, keys.tenantId, { tokenAudience: 'graph' } ...

The page keeps refreshing repeatedly

Can someone help me troubleshoot this url modification script? var currentPath = window.location.href currentPath=currentPath.replace(/&amp;/g, "&"); window.location.href=path; It seems like the page keeps reloading endlessly... Any sugg ...

Modify the properties of an element based on another

Situation : I am facing a challenge where I need to adjust two components based on a click event. The function linked to the onclick event handleChange includes a prop 'text'. Each time the onclick event is triggered, I must modify the value of t ...

Ensuring Bootstrap 3 Table Header Widths Remain Fixed

How can I ensure the header columns in my Bootstrap 3 table maintain a fixed width, regardless of the content in the regular rows? I want to avoid the messy look of content splitting onto multiple lines. Here's an example: I'd prefer not to adju ...

Just starting out in the world of CSS - mastering text arrangement and styling

This is my first attempt at writing CSS code. I would like to align all rows of the same block together, but I'm unsure of how to go about it. Here is what I'm attempting to achieve: If I were using regular HTML, I would simply create a table wi ...