Prevent all elements sharing the same class from expanding upon clicking if their parent element

Currently, I have implemented a function as a click event callback on a button. The purpose of this function is to toggle the class and provide a dropdown effect when the button is clicked. While this functionality works perfectly when the dropdown element is located next to the clicked button's parent element, it fails to work when the dropdown element is placed outside of the parent. The issue arises because there are multiple buttons with the same functionality on the page, causing all of them to trigger when just one is clicked:

https://jsfiddle.net/21xj96up/7/

$('.direction-button').on('click', function() {

  $(this).next('.direction-dropdown').toggleClass('active');

});
.fade-in {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s, opacity .3s ease-in-out, all .3s ease-in-out;
}
.active {
  visibility: visible;
  opacity: 1;
  transform: translate(0, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script>
<div class="contact-card">

  <div class="contact-directions">

    <a href="#" title="#" class="direction-button link-button animate-after">Directions</a>

  </div>
  <!-- end .contact-directions -->

  <div class="contact-info"></div>
  <!-- .contact-info -->
  <div class="contact-partner"></div>
  <!-- end .contact-info -->

</div>
<!-- end .contact-card -->

<div class="direction-dropdown fade-in">

  <p>Display #1</p>

</div>

<div class="contact-card">

  <div class="contact-directions">

    <a href="#" title="#" class="direction-button link-button animate-after">Directions</a>

  </div>
  <!-- end .contact-directions -->

  <div class="contact-info"></div>
  <!-- .contact-info -->
  <div class="contact-partner"></div>
  <!-- end .contact-info -->

</div>
<!-- end .contact-card -->

<div class="direction-dropdown fade-in">

  <p>Display #1</p>

</div>

I would greatly appreciate any advice or assistance on resolving this matter :)

Answer №1

Ensure that there is a container labeled as "parent-container" with the name contact-card, if it exists, proceed with the next steps from there; otherwise, continue with the current process:

https://jsfiddle.net/21xj96up/12/

$('.direction-button').on('click', function(){
    if( 1 === $(this).closest('.contact-card').next('.direction-dropdown').length) {
        $(this).closest('.contact-card').next('.direction-dropdown').toggleClass('active');
    } else {
        $(this).next('.direction-dropdown').toggleClass('active');
    }
});

Upgrade to a more "concise" version https://jsfiddle.net/21xj96up/21/ This improved version utilizes the same

$(this).closest('.contact-card').next('.direction-dropdown')

query twice. By saving it to a variable and reusing the variable, we enhance efficiency.

$('.direction-button').on('click', function(){
    var parentElement = $(this).closest('.contact-card').next('.direction-dropdown');
    if( 1 === parentElement.length) {
        parentElement.toggleClass('active');
    } else {
        $(this).next('.direction-dropdown').toggleClass('active');
    }
});

Answer №2

This particular code is my recommendation for handling the selection conditions as they are not identical:

$('.direction-button').on('click', function(){
  var btn = $(this);
  if(btn.parents('div').length>0) {
        btn.parents('div').next('.direction-dropdown').toggleClass('active');
  } else {
        btn.next('.direction-dropdown').toggleClass('active');
  }   
});

Answer №3

When dealing with situations where the element-hierarchy is inconsistent, utilizing data-attributes and IDs can help make toggler and content independent of hierarchy.

Data attribute for the Toggler:

data-toggle-target="display1"

ID for the target

`id="display1"`

The jQuery script to toggle the class

$( '#' + $(this).attr('data-toggle-target')).toggleClass('active');

Link to JSFiddle example

Answer №4

Within your code, when $(this) is within the context of $('.direction-button'), it actually refers to the "direction-button". There isn't a subsequent "direction-dropdown" associated with the same level of "direction-button".

div
    div
        direction button
        <it looks for the item here>
    /div
/div
<item is actually here>

You can attempt this approach:

$(this).parent().parent().next().toggleClass('active');

This will help you achieve the desired functionality in the second scenario.

Answer №5

To achieve optimal results, it would be beneficial for the structure to remain consistent. However, if you are unable to control this aspect, you may also lack authority over additional classes or ids that could offer a more effective solution. In such circumstances, determining the index of the current button within a collection of all buttons and dropdowns can help locate the next dropdown in the sequence.

var idx = $(this).index('.direction-button, .direction-dropdown');

$('.direction-button, .direction-dropdown')
    .slice(idx)
    .filter('.direction-dropdown')
    .first()
    .toggleClass('active');

Here is an example: https://jsfiddle.net/j7h32w90/1/

This approach is versatile and applicable in various DOM structures.

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

Function for verifying presence of empty nested elements (comprising of Arrays, Sets, Strings, and Maps)

I am currently exploring ways to develop a solution using plain JS (without relying on any external libraries) that can determine whether a given input is considered 'empty' or not. Below are the code snippets and test cases I have prepared for ...

Why is my React Native component not getting the props it needs?

Transitioning from my experience with React, I initially believed that passing props worked the same way, but it turns out that's not the case? Currently, I am working on a login form where I want to differentiate between the styling of the sign in a ...

AngularJS Controller assigns unexpected value to object

While working on a project, I encountered an issue with assigning float values fetched from a REST API using Angular. Instead of correctly assigning the float value, it was being set as 0. To illustrate my problem clearly, let's consider the followin ...

Send an identifier to the following page upon selecting a hyperlink in AngularJS

I am currently working on a project that involves displaying a list of places and allowing users to click on a place to view more details on another page. I would like some guidance on how to implement this feature. Here is the HTML code for Page1: <l ...

What is the best way to ensure that the scroll position on each page in shinydashboard remains unaffected by changes in the scroll position on other pages?

When navigating between pages A and B in my shinydashboard app, I noticed that the scroll position of one page affects the scroll position of the other. How do I make the scrolls independent? To illustrate my issue, I've included a stable shinydashbo ...

The HTML form must be able to determine the number of records in the database

I am facing an issue with my HTML form written in PHP, where there are one or two checkboxes based on the user's selection from a dropdown earlier in the form. The challenge lies in determining how many records meet the query conditions in an SQL data ...

Hover over the Div element for inline effect

Hello all, I am currently working on running a while loop from a database to show different records. The twist is that these records are displayed as images, which makes it tricky to customize using standard CSS. To work around this, I'm implementing ...

What is the most efficient way to retrieve the two smallest numbers using jQuery?

I am trying to find the two smallest numbers out of a set of three, and then I want to display them on the screen. In PHP, we usually use echo to display values on the screen. However, with this code snippet, I am only able to get one smallest value instea ...

Monitoring changes in the size of the parent element with an AngularJS directive

Issue I am facing a challenge with a directive that updates the size of an element based on the window size. The directive monitors changes in window dimensions and adjusts the element accordingly. MyApp.directive('resizeTest', ['$window&a ...

Is there a way to restrict the number of words displayed in React? Check out this code snippet: `<ProductImg imgtext={products.description}/>`

imgAlt={product.name} Note: Consider the product name as: HD Single Sided Cantilever Rack. In this case, only HD Single Sided... should be displayed Please find the code snippet below <ProductImg imgtext={products.description}/> ...

What is the process for uploading a file selected with the Dojo Uploader to a servlet using Dojo version 1.7.5?

I've been struggling to find a proper method for posting a file selected using dojox.form.Uploader to my servlet. Unfortunately, there is limited documentation available for Dojo and not many examples, demos, or tutorials to follow. Any help with this ...

HTML 4.01 character and character offset attributes

I'm curious about the purpose of the charoff attribute in HTML 4.01 Transitional. Specifically, consider a table column that contains the following cells: <td>1.30</td> <td>10</td> <td>100.2</td> <td>1000 ...

The JQuery .replaceWith method exclusively offers unprocessed HTML content

I'm experiencing a minor issue with my ajax response where it returns raw html and does not execute any scripts, resulting in the jquery ui scripts not being executed. Here are some details: I am currently working with ASP.NET MVC and I need to comm ...

Is there a method to dynamically disable Angular Multiselect (Cuppa Labs)?

I am currently using a multi-select dropdown feature by Cuppa Labs that can be found at this link. However, I am facing difficulties in disabling the dropdown. Initially, setting disabled:true in the settings works fine. But I require it to be disabled:fa ...

What could be causing this code to malfunction in Internet Explorer 7?

Code: Demo: In the majority of modern browsers such as Safari, Chrome, Firefox, and IE8/9, the code works perfectly fine. However, there seems to be an issue with IE7, causing it not to work. Any idea why this might be happening? My goal is for the conte ...

Problem arises when attempting to display a div after clicking on a hyperlink

I'm encountering an issue with displaying a div after clicking on a link. Upon clicking one of the links within the initial div, a new div is supposed to appear below it. All tests conducted in jsfiddle have shown successful results, but upon transf ...

jQuery Mobile persists in loading the initial page of a multi-page document after form submission

After searching extensively for an alternative to data-ajax="false" without success, I've found myself in a dilemma. In my Phonegap application, utilizing jQuery Mobile to submit a form requires running it through the standard submit function in jQuer ...

Discover the Google Chrome Extension that allows you to easily obtain JSON data from your

Here is the structure I have: And below is my manifest.json: { "manifest_version": 2, "name": "Doktor-MD", "description": "Share links on Doktor-MD through the browser.", "version": "1.0", "permissions": [ "http://www.google.com/" ], "browser_action": ...

"Combining multiple attributes to target elements while excluding specific classes

My dilemma lies in the following selector that identifies all necessary elements along with an extra element containing the "formValue" class which I aim to omit $("[data-OriginalValue][data-OriginalValue!=''][data-TaskItemID]") ...

Design a Label or Tab with Pure CSS

Is it possible to achieve a tab or label-like look using only CSS, without the need for images? This is what I am aiming for: While I can create one end, I am struggling to create the triangle point. Can this be accomplished solely with CSS? ...