Consolidating various analogous operations into a single function

After scouring through StackOverflow in search of a solution to what I perceive as a simple issue, I have come up empty-handed. It seems like I may be using the wrong keywords in my search.

I am interested in finding out how to condense the following code into just a few lines. Essentially, when 'link-#' is clicked, it should display the content from the hidden div 'more-#' (where the number in 'more-' corresponds to the number in 'link-#'). The current code snippet looks like this:

jQuery("#link-1").click(function(){
    jQuery('#more').hide().html($('#more-1').html()).fadeIn(400)
});
jQuery("#link-2").click(function(){
    jQuery('#more').hide().html($('#more-2').html()).fadeIn(400)
});
jQuery("#link-3").click(function(){
    jQuery('#more').hide().html($('#more-3').html()).fadeIn(400)
});

and so on.

I have attempted to come up with a more efficient way to achieve this by writing the code snippet below, however, it does not seem to work as intended.

jQuery("#link" + NUMBER ).click(function(){
    jQuery('#more').hide().html($('#more-' + this.NUMBER).html()).fadeIn(400)
});

If anyone has insights on how to properly address this issue, I would greatly appreciate your assistance.

Thank you in advance for your help.

Sincerely,

Thomas

Answer №1

One effective strategy is to group similar items together by assigning them the same class, and then use a data-* attribute to link them to their corresponding element:

jQuery(function() {
  jQuery(".show-more").click(function() {
    var target = $(this).data('target');
    jQuery('#more').hide().html($(target).html()).fadeIn(400);
  });
});
#moreItems {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<a href="#" class="show-more" data-target="#more-1">Show More 1</a>
<a href="#" class="show-more" data-target="#more-2">Show More 2</a>
<a href="#" class="show-more" data-target="#more-3">Show More 3</a>
<div id="more"></div>
<div id="moreItems">
  <div id="more-1">Here are the details 1</div>
  <div id="more-2">Here are the details 2</div>
  <div id="more-3">Here are the details 3</div>
</div>

Answer №2

Assign the same class name to all elements and then include the attribute "data-num" in each of them. After that, implement the following jQuery script:

jQuery(".className").click(function () {
    var $this = $(this);
    var html = jQuery('#more' + $this.attr('data-num')).html();
    jQuery('#more').hide().html(html);
});

For instance, in your HTML:

<a class='className' data-num='1'>Link</a>
<div id='more1'></div>
<div id='more'></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

Transforming an older React website with react-helmet-async

I am working on a React site that is client-side rendered and I want to use the react-helmet-async module (version 1.0.7). Here's my scenario in the React app: /public/index.js: <head> <title>My title in the index file</title> ...

Altering the color of a Fabulous Icon in real-time

I'm having trouble changing the color of an Awesome Icon with this code I created. Instead of getting the desired color, I am getting 'undefined' as a result. <script type="text/javascript"> function changeAIColor(idName) { alert ...

Is there a way to dynamically count the length of an element or class in realtime using JavaScript?

If there are currently 5 divs with the class name "item" and a new unknown number of divs with the same class name "item" are dynamically added in real time, I want my result to display the total number of divs present at that moment (i.e., 5 + n). Note: ...

Is there a way to control the text animation loop on iTyped, both starting and stopping it?

Currently utilizing React, MUI, along with iTyped The animation implemented involves backspacing text and typing the next word in a specified array until reaching the final word. I am looking to enable a click function on the div containing this animation ...

Experiencing issues where an undefined value is being returned while attempting to pass a selected value

I'm facing a minor issue with my JavaScript code. Below is the form structure I am working with: <form method="get" name="basic" id="basicId" action="/page2"> <select id="activity" name="activity" class="form-control inputbox"> ...

A customizable checkbox component in React that includes an image and doesn't require an

I am working on creating a versatile React component for checkboxes. After familiarizing myself with the traditional image-replacement technique for checkboxes, I have implemented it in my React code: import React, { Component } from 'react'; ...

I aim to create a tool that randomly selects numbers, although the outcome often exceeds initial expectations

My page is filled with various items, and among them, I have a random number generator. When I tested it, the result turned out to be higher than expected. Can anyone help me figure out why? Here's the code snippet: <div> <h2>G ...

Using JavaScript to send form input in the form of a 2D array through AJAX

I am currently working on a form that looks like this: <form name="chat" id="chat" action="" onsubmit="sendMessage()"> <a name="chat">&nbsp;</a> <input type="text" name="chat" id="chat" size="38" maxlength="50" vertical-align="m ...

JavaScript - Output an undefined value of a property within a function

While the question of checking for null or undefined values has been raised before, I am encountering a unique issue. I have created a function to split a string, which works perfectly. However, when I pass a null or undefined value, the program stops. Ins ...

Tips for adjusting the transition speed duration in Bootstrap 4

Is there a way to enhance the smoothness of image slides? I can adjust the speed between slides using data-interval, but how do you tweak the speed within each slide? According to the documentation: .carousel-item{ transition: transform 5s ease, opacit ...

Enhance your website with a dynamic jQuery gallery featuring stunning zoom-in

I am currently working on a mobile website project and I'm in need of a gallery feature that allows users to zoom in on images and swipe through them using touch gestures. After some research, I haven't been able to find a suitable solution in j ...

Troubleshooting video streaming loading issues caused by 404 errors in URL paths with videojs

I've been successfully using the video.js library to stream live video. Everything was going well until after a while, the URL started throwing a 404 error during streaming, causing the entire player to get stuck on loading. Now I'm looking for a ...

Issue with scrollHeight in Vue.js component

I am currently using Vue and have a div tag styled with CSS var max_pages = 100; var page_count = 0; function snipMe(el) { page_count++; if (page_count > max_pages) { return; } var h = parseInt(window.getComputedStyle(this, null).getP ...

A guide to resizing a canvas correctly in React with the help of p5.js

Currently, I am working on a project that involves resizing the model in the canvas when the canvas or window is resized. I have consulted the documentation for resizeCanvas() and implemented it. To achieve this, I first determine the ratio by dividing th ...

How to prevent panning on mobile devices in Three.js using Javscript?

Currently working on my 3D project using three.js and everything is running smoothly on my laptop. I'm utilizing OrbitControls for camera movement, but I have disabled right-click panning to only allow camera rotation. However, when testing on a mobil ...

BookshelfJS: Establishing a One-to-One Relationship

Within my database, I am working with two tables - User and Address. The User table consists of the following two methods: shippingAddress: function() { var Address = require(appRoot + '/config/db').model('Address'); return thi ...

Ways to implement routerLink in the parent component for commonly used components

I've been working on an Angular 6 app that utilizes the Rest Country API to retrieve information about different countries. The challenge I'm currently facing is understanding how to configure the routerLink in the parent component to access coun ...

PHP - working with multidimensional arrays and iterating through them

I manage a website that houses a vast collection of books; each book has its own dedicated information page (like ). <html> <body> <div class="book"> <div id="author">Author</div> <div id="title">Title</div> <d ...

"Exploring the world of Sharepoint Online WebParts with a touch

Recently, I decided to migrate a website that I previously built in SharePoint 2013 to be a Sharepoint Online WebPart. After doing some research, it seems like WebParts are typically created using TypeScript. Is TypeScript really the only way to go about b ...

Mastering the art of transitioning between DIV elements

I am looking to implement a rotating three-card display on click, and have come up with the following code: $('.box1').click(function(){ $('.box1').toggleClass('removeanimate'); $(this).toggleClass('go'); ...