Jquery toggle not functioning properly with two classes - looking for a solution using a multiple class selector

Here is the link to my code: http://jsfiddle.net/GwUmb/4/

    $(document).ready(function(){
    $(".trigger,.trigger-2").click(function(){
        $(".panel,.panel-2").toggle("fast");
        $(this).toggleClass("active");
        return false;
    });
});

I've been facing an issue with loading panel-2 from trigger-2...The behavior of .trigger and .panel seems somewhat correct, but there are some strange CSS styles applied.

When I remove .panel-2 and .trigger-2, the code works perfectly fine. However, when those classes are included, it doesn't work as expected.

I was attempting to reproduce what I found in this resource: http://www.w3schools.com/jquery/sel_multiple_classes.asp.

Answer №1

The challenge at hand is that when any trigger is clicked, all panels are activated simultaneously because both are selected and toggled using the same function. To address this issue, one solution is to store the panel's corresponding index as data on the trigger element, or alternatively, use the index directly which could be more effective for your situation.

$(".trigger").click(function(e) {
    $(".panel").eq($(this).index(".trigger")).toggle("fast");
    $(this).toggleClass("active");
    e.preventDefault();
});

http://jsfiddle.net/GwUmb/6/

Answer №2

If you're looking for an alternative approach, consider using a single class name for your links or containers. By streamlining your code and adding a hover function to handle link displays, you can achieve better organization. Using a CSS method with lists might also simplify the process...

Check out this live example here

Here's the updated jQuery:

$(document).ready(function() {

                //keeping track of the current selected link
                var $link;

                $('.trigger').hover(function() {
                    $link = $(this);
                    //get position of clicked link
                    var linkPos = $link.position();
                    //position & display this links panel
                    $link.toggleClass("active");
                    $link.siblings('.panel').css({
                        'top' : linkPos.top
                    }).fadeIn(600);

                }, function() {//hide the panel on mouseout
                    $link.siblings('.panel').slideUp(600);
                    $link.removeClass('active');
                });

            });
            // end ready

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

Using jQuery to temporarily disable a div element

I need to implement a timer in a div that will disable it for a specific duration, such as 3 seconds. Here is the HTML code snippet: <div class="answ-container" align="center"> <div class="c_answer" id="1316" name="1" data-rcat-no="1"> ...

Order of operations during synchronous $.ajax request handling

I'm grappling with understanding how synchronous ajax calls impact the order of execution as I encounter some peculiar bugs. // (1) $.ajax({ async: false, url: url0, dataType: 'json', success: function(data) { // (2) }); / ...

Creating an array of logos in ReactJS with the help of TailwindCSS

After seeing multiple implementations of this feature, I find myself struggling to search for a solution. I can only access the HTML and CSS through inspecting elements, wondering if others are facing the same issue as me. Typically, we aim to implement t ...

What is the process for incorporating gradient hues on top of a chart line?

Here I am experimenting with gradient colors at the top of the chart area by reversing the y-Axis. You can see the effect in the image below. yAxis: { reversed: true, showFirstLabel: false, showLastLabel: true } https://i.sstatic ...

How can I access a nested FormArray in Angular?

I have a situation where I am trying to access the second FormArray inside another FormArray. Here is an excerpt from my component: registrationForm = new FormGroup({ registrations: new FormArray([this.patchRegistrationValues()]) }); patchRegistrati ...

Is the use of htmlspecialchars() in jquery .html() function sufficient to prevent javascript attacks when retrieving data through ajax requests?

I have developed a PHP and jQuery-AJAX script that performs well. However, I have noticed that it runs slowly and is vulnerable to XSS attacks. Upon researching further, I came across some relevant information in the first answer of this link: please see t ...

Textarea focus() function not functioning as expected in Chrome Extension with dynamically added text

Although I have come across many similar questions, it appears that I am still missing a key piece of information. My issue revolves around appending an HTML div tag upon clicking a button. Within this appended div tag lies a textarea tag that should auto ...

Ways to retrieve dropdown values

My HTML code is as follows: <select class="height_selected"> <option>Select Height</option> <option ng-model="userHeight" ng-init="1" value="1">123 cm</option> <option ng-model="userHeight" ng-init="2" v ...

Executing actions on events in a Basic jQuery sliderLearn how to handle events and execute

I utilized the slider from the bjqs plugin at after reviewing the documentation, I noticed it only offers options and lacks events/functions. I am referring to events/functions like onSlideChange and onSlideDisplay. While other plugins such as bxslid ...

Updating array with user input using Ajax

For the past few days, I have been struggling to extract data from a PHP page (array) and store this data in a jQuery array. The issue arises when trying to send data to the PHP page using the following code: $.ajax({ type: "POST", url: 'test ...

Trying to connect a webpage to my CSS file

Lately, I've been diving into building a new website. It's still in its early stages and unfortunately, I'm struggling to get the style.css file to cooperate. Despite my best efforts scouring the internet for fixes, I haven't had much l ...

How to centrally align grids in a material-ui react application

I'm trying to center Grid items horizontally inside a Grid container, while also adding some spacing between the items. Here's the code I have so far: import React from "react"; import { makeStyles } from "@material-ui/core/styles& ...

Does jQuery UI Layout have compatibility issues with jQuery version 3.3.1?

jQuery UI Layout is compatible with older versions of jQuery, but not with newer versions... Here is a working example: <html> <head> <script src="http://layout.jquery-dev.net/lib/js/jquery-1.4.2.js"></script> <script ...

The Jquery selector is not functioning properly when used with an ajax response

After receiving the data from an ajax response, I have added it to the DOM. <label class="switch"> <input name="new" value=1 type="checkbox" id="switchButton" data-id="'+order.i ...

Revolutionizing Zen Cart with slimMenu

Is there a smarter person out there who can help me understand why the slimMenu is breaking when I add these files to the bottom of the page? <link href="includes/templates/westminster_new/css/age-verification.css" rel="stylesheet"> <script src=" ...

The width of the Div element is not following the specified dimensions, and it also has an unspecified margin

Check out my code snippet at: http://jsfiddle.net/8z4aw/ I'm trying to create a table-like layout using div elements, but for some reason the browser is not respecting the specified widths and seems to be adding an unwanted right margin. Where is thi ...

How can PHP effectively communicate errors to AJAX using jQuery?

I have been on the lookout for a straightforward, neat, and adaptable method to send error messages back to the browser following a POST or GET request. Here is an AJAX example using jQuery: $.ajax({ data : { method : 'example', inp ...

Is there a way to adjust the orientation of a <video> element without affecting the orientation of the video controls?

<video controls> </video> video { transform: scaleX(-1) } This CSS code flips the video horizontally, but it also flips the control buttons along with it. I attempted to flip the wrapper element containing the video using .wrapper {transfor ...

Verify whether the input field contains a value in order to change certain classes

My meteor-app includes an input field that dynamically changes position based on whether it contains content or not. When a user begins typing, with at least one character, the input field moves to the top of the page. In my current approach, I am using a ...

Failure to update content with new text in Ajax when GET/POST variables are included

I've been following a tutorial on Ajax functionality, and I have set up my code exactly like mmtuts. However, the new value isn't displaying until I make an adjustment to my test.js file: The original code that is not functioning as expected: $ ...