Connecting various components together

I am attempting to establish a connection between various elements in order for a specific class element to trigger an action on another specific class element (for example, when .ph5 is clicked, .art5 should become visible)

Here is what I have developed so far:

var back = [$(".art1"), $(".art2"), $(".art3"), $(".art4"), $(".art5"), $(".art6"), $(".art7"), $(".art8"), $(".art9")];
var front = [$(".ph1"), $(".ph2"), $(".ph3"), $(".ph4"), $(".ph5"), $(".ph6"), $(".ph7"), $(".ph8"), $(".ph9")];

$('front').click(function(e) {
  var clicked = $(e.clicked);
  for (var i = 0; back.length; i++) {
    if (clicked.is(front[i])) {
      back[i].show();
    }
  }
});

Unfortunately, this implementation does not seem to be functioning as expected. Could there be an error in my code, or is there a more effective method of "linking" multiple classes together?

Answer №1

If you assign them all the same common class, the process becomes even easier. By using the index() method, you can determine the index of an element within a collection, and then utilize the eq() method to target another set of elements (assuming that both sets are in the same order).

var $front = $('.ph'); // all elements share the same class
$front.click(function(){
   var index = $front.index(this); // index of the clicked element within the collection
   $('.art').hide().eq(index).show();  // hide all elements, then show the element at the matching index  
});

References:

index() API Documentation

eq() API Documentation

DEMO

Answer №2

There is a more simplified approach using a jQuery selector element[attr^='value'], which can target all elements with an attr that starts with value.

$("div[class^='ph']").click(function() {
  var newid = $(this).attr("class").replace("ph", "art");
  $("." + newid).show();
});
.art1,
.art2,
.art3 {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div class="ph1">ph1</div>
<div class="ph1">ph1</div>
<div class="ph2">ph2</div>
<div class="ph2">ph2</div>
<div class="ph3">ph3</div>
<div class="ph3">ph3</div>
<br>
<div class="art1">art1</div>
<div class="art1">art1</div>
<div class="art2">art2</div>
<div class="art2">art2</div>
<div class="art3">art3</div>
<div class="art3">art3</div>

Answer №3

To access array elements, avoid using front[i] and back[i]. Instead, create an array object and access elements using the .eq() selector:

$(front).click(function(e) {
  var clicked = $(e.clicked);
  for (var i = 0; back.length; i++) {
    if (clicked.is($(front).eq(i))) {
    $(back).eq(i).show();
  }
 }
});

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

Conceal rows in a table that are not selected using Jquery when the table has been loaded from a given URL

Below is the HTML code for an user search input field and the results table: <div class="input-group"> <input type="text" id="q" class="form-control" placeholder="Search for User"> <span class="input-group-btn"> ...

Is Amazon altering the names of their CSS selectors and HTML elements on the fly?

For my Amazon.es web scraper built with Selenium, I am using a CSS selector to determine the total number of pages it will iterate through. However, the selector name seems to change dynamically and I must update it daily. As someone not well-versed in H ...

Whenever I try to open my jQuery UI Dialog without first displaying an alert, it does not work

Beginning of my HTML page, initializing a dialog : <script type="text/javascript"> $(function() { $( "#dialog-confirm" ).dialog({ autoOpen: false, resizable: true, height:180, width:300, modal: true, buttons: { "Yes": ...

What are some effective strategies for keeping content from shrinking in a drawer menu?

I am currently using a tutorial from https://www.w3schools.com/howto/howto_js_sidenav.asp to create a drawer sidebar menu. However, in my scenario, I need to include a wall of text instead of <a> links. The issue I am facing is that the text expands ...

Ways to verify if the user has inputted a typeahed value

My code snippet looks like this: var students = new Bloodhound({ datumTokenizer: Bloodhound.tokenizers.obj.whitespace('fullName'), queryTokenizer: Bloodhound.tokenizers.whitespace, remote: { ...

Disable the default page scrolling behavior when collapsing an accordion section in Bootstrap 4 framework

Incorporating a Bootstrap 4 accordion with an expanded body section that causes the content below to scroll up when collapsed. To address this issue, attempting to scroll to the top of the clicked header and prevent undesirable scrolling from the collapse ...

Guide to center align fields in Ionic and Angular

I am working on creating a login screen that resembles the image provided. I have managed to set the background image, input fields, and buttons successfully. However, I am encountering a few issues: The width of my input field is taking up the entire spa ...

Tips for keeping an image stationary when hovering over it

I'm in need of some assistance. Despite my best efforts, I have been unable to achieve the desired outcome. I am looking to create a scenario where an image remains in place even when the mouse hovers over it. Essentially, I want the image to stay vis ...

Generating safe HTML output in PHP requires adding 4 spaces before the code

I'm currently designing a form that generates basic HTML and other plain text output for users to copy and paste into a content management system. For setting up the variables, I follow this structure: $date1 = $_POST['date1']; $city1 = $_ ...

Achieve the effect of making the Bootstrap JS Collapse text bold after it has been

Is there a way to make Bootstrap JS Collapse text Bold after it has been clicked on? <tr data-toggle="collapse" data-target="#demo8" class="accordion-toggle"> <td> <div class="fa ...

I'm having issues with my flipclock moving too quickly and skipping over certain numbers. Any suggestions on how to resolve this issue?

My flip clock script is behaving oddly, moving too quickly and skipping over even numbers. I've been playing around with the code, and it seems like there's a problem when I use the callbacks function. var clock = $('#clock3').FlipClo ...

Implement a procedure for printing a page once the columnize operation has been completed

Hello, I have run into a problem that I need help with. Currently, I am trying to print a page after the function "columnize" has finished its task. However, the print function is executing before the columnize function completes. How can I ensure that t ...

Enhance text content effortlessly with an automated text augmentation feature

Essentially, what I'm wondering is whether there exists a program that can automatically add HTML tags to the text you input. For instance: Let's say I type in: "The world is beautiful" The program would then transform it into: <p align="c ...

Preserving data and retrieving it

I've been working on a program for my diving coach that calculates the dive score as judges input their judgments. However, I'm encountering an issue where all fields clear themselves when I hit submit. Moreover, I'd like the ability to save ...

What is the best way to make a block fill 100% of a container-fluid?

Here is a block: <div class="container-fluid"> <div class="content_wrapper"> </div> </div> What's the best way to display the .content_wrapper block with 100% content width and margins from the body borders? ...

Strategies for Implementing Multi-Step Password Form Validation

Currently, I am using https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_form_steps as the foundation of my form with some adjustments. Validation is functioning correctly where empty fields disable the next button. However, when I attempt to add ...

Unable to align a 1px element with the primary border

Can you please assist me? I would like to modify the CSS markup below in order to remove the 1 pixel added extra on the active clicked tab from my UL LI Tabbed Menu. How can this be achieved? Here is a picture of the issue: HTML Markup: <div class=" ...

How can I maintain my bottom navigation bar in Bootstrap 3 without using a 3 span icon?

Hey everyone, I'm still getting the hang of MVC as I only started using it around 3 weeks ago. Currently, I am working on a Web Application where I am trying to implement a specific feature: At the bottom of the page, I have a navbar with some Html. ...

What is the solution to resolving an Open Quote error message in HTML coding?

Seeking assistance to resolve an HTML code error located at line 9. Fatal Error: Open quote is expected for attribute "{1}" associated with an element type "border". The problematic code snippet is as follows: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML ...

Getting rid of the hover box feature in a WordPress theme

Having some difficulty removing the hover effect on the WordPress theme I'm using, called Enigma. The hover effect creates a whitebox over the link, and despite trying various methods to remove it, the issue persists. You can view the website at the ...