I'm not entirely sure how JQuery processes the .each() function and the (this) keyword

I'm still learning JQuery and trying to figure it out. Can you help me understand what's going wrong with my code below?

I have multiple content blocks with classes .acc-0, acc-1, and so on. I want to show and hide the .plans-breakdown when the .open-link button inside each block is clicked.

Here is an example using .acc-1:

$('.acc-1').each(function(){
        $(this).find('.open-link').on('click',function() {
            $('.plans-breakdown').not(this).css('display','none');
            $(this).find('.plans-breakdown').fadeToggle(600);
        });
    });
    

HTML:

<div class="schedule-plan acc-0">
    <div class="open-link">Floor plan acc-0</div>
        <div class="plans-breakdown">
            content here
        </div>
    </div>
    </div>
    <div class="schedule-plan acc-1">
    <div class="open-link">Floor plan acc-1</div>
        <div class="plans-breakdown">
            content for acc-1 here
        </div>
    </div>
    

I want this functionality to only work for the specific code block, in this case, .acc-1. That's why I wrapped the function in $('.acc-1').each(function(){}.

I used (this) to target the correct .open-link button for the function. Also, for the .fadeToggle action, I specified the instance of .plan-breakdown nested inside .acc-1.

Take a look at my fiddle. You'll see that the first block works (.acc-0), but when I use .each, it doesn't.

http://jsfiddle.net/bazzle/Q4zmS/2/

Thank you.

Answer №1

Try out the Demo Fiddle

Here is a simple solution you can implement:

// for every element with a acc- class...
$('[class*=acc-]').on('click', function () {
    // hide all previously shown elements
    $('.plans-breakdown').css('display', 'none');
    // fade in the child element
    $(this).find('.plans-breakdown').fadeToggle(600);
    // remove active class from all links
    $('.open-link').removeClass('active');
    // add the active class to the child link
    $(this).find('.open-link').addClass('active');
});

In addition, you should include the following in your CSS to eliminate the need for JS:

.plans-breakdown{
    display:none;
}

Furthermore, you need to adjust your CSS to correct the nested rules. Here is the recommended CSS:

.schedule-plan {
    display:block;
    padding-top:.3em;
    cursor:pointer;
}
.active {
    color:black;
}
.plans-breakdown {
    margin:1em 0 2em 0;
    cursor:default;
}
.plans-breakdown {
    display:none;
}

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

What Could Be Causing My Webfonts to Be Inaccessible on Windows Devices and iPhones?

I recently created a simple holding page on www.tomrankinmusic.com The Webfonts I embedded in the page display correctly in the latest versions of Firefox, Safari, and Chrome on Mac OSX Lion 10.7.4 but do not show up in Chrome and IE6 on Windows XP Pro, d ...

Tips for placing a background image on an extended <a> hyperlink in Internet Explorer 6

There seems to be an issue with the background image of a link on my exam project. The requirement is for it to work seamlessly on all browsers, including IE 6. However, the problem arises when the link spans multiple lines in IE 6, causing the background ...

Javascript function that sets the opacity to 0

Hello everyone, I'm new to SO and seeking some guidance on improving my post! I have a function that sets the opacity of an element to 0 in order to clear it. While this works fine, it becomes burdensome when dealing with multiple elements that requi ...

Ways to combine multiple CSS styles for an element using .css()

I'm struggling to apply styles to a deeply nested element using jQuery and JavaScript. I understand how to style nested elements, but I'm having trouble targeting a specific deeply nested element. My website is built on WordPress, and it has ins ...

How can the id of the parent element be retrieved within this function?

Is there a way to retrieve the ID of the parent element within the same function and log it in the console? I attempted to obtain the ID of the parent element that I bound the function to. $('#customized-player').mediaelementplayer({ al ...

What steps should I take to ensure my Bootstrap CSS3 code is error-free and W3C validated?

My customer is requesting that I validate the HTML5 & CSS3 code using W3. I plan on incorporating Bootstrap 3.3.4 into the project, but after including it and checking at , I discovered 32 errors and 142 warnings. The W3C CSS Validator results for (C ...

Execute script when the awaited promise is fulfilled

I am looking to retrieve the URL of a cat image using the Pexels API through a script, and then set that image link as the source of an actual image element. I attempted to include some loading text to keep things interesting while waiting for the image l ...

tips for managing the backspace key in the key up event handling

I have a record stored in a database with the names Charles, Dale, Jack, and William. Using PHP code, I am able to retrieve this data from the database and display it initially. I have also added a text field where any of these four names can be entered, a ...

Discovering the font-weight attribute in Selenium IDE

Currently, I am working with Selenium IDE and aim to detect when a text element has the 'font-weight:bold' CSS property applied to it using 'verifyAttribute'. The specific CSS locator being used is: css=body.home.es ul#languages li:nt ...

The issue with sending Ajax post data in Internet Explorer 10 has been identified

After spending hours researching this issue, I am still unable to find a solution. It seems that Internet Explorer 10 is able to submit ajax requests using jQuery, but it does not include the post data. Below is the code snippet in question: var ajaxDat ...

Moving icon that appears when hovering over a menu button

Before diving into this, please take a moment to visit the following website to understand my goal: You'll notice there is a noticeable RED arrow positioned below the menu. What I aim to accomplish is... when I hover over a menu button, the arrow smo ...

Show equally sized elements using a grid system

I need assistance with displaying fields in a row using CSS grid. I want to display 3 fields in a row with equal width, and if there are only 2 fields, they should also have equal widths. Additionally, if there is only one field, it should take up the full ...

Positioning of the navigation menu

After customizing my Bootstrap navbar, I noticed that when the responsive size changes to mobile, the burger menu opens on the left side. Is there a way to move it to the right? Any help would be appreciated. Here is the HTML code: <!DOCTYPE html> ...

Struggling with textpath SVG elements in jQuery

Currently, I am implementing SVG in my project and aiming to apply the toggleClass function using jQuery on the textpath elements upon clicking. My initial plan was: $("text#names > textpath").click(function() { $(this).toggleClass("newClass"); }) ...

Move your cursor over an image within a div container

After not finding any helpful answers on this topic, I've decided to ask for help again. My issue involves having an image inside a div. <div id ="gratterlendis"> <a href ="?page_id=8"><img src="img/gratterlendis.png" align="right" wid ...

A sleek fixed navbar in Bootstrap showcasing a shrunk logo positioned above the navbar

Is there a way to implement a fixed navbar with a parent logo using bootstrap? I would like the logo to shrink as you scroll, while still remaining visible within the fixed navbar. For a demo of the shrinking logo and navbar, you can visit: ...

Switch between various API content upon clicking (JavaScript)

Upon receiving data from an API in JSON format using PHP, I aim to incorporate a filter mechanism for displaying distinct content sourced from the API. For instance, by specifying a filter in my API call, I can retrieve separate datasets such as one with ...

Mantine - Showing search results in a scrollable list that stops at the parent's height and then adds vertical scrolling

I am currently in the process of developing a web application that needs to occupy the entire height and width of the screen using 100vh and 100vw. The main app itself should not have any vertical or horizontal scrolling, but individual components/divs wi ...

Steps for designing a stationary footer in HTML and CSS

I have implemented a static footer on my website: HTML <div class="card fixedFooter"> <div class="card-body space-around"> <button type="button" class="buttonFooter" routerLink="/myRouter" > <i class ...

No animation will be applied to slideUp() on a specific block without using jQuery

I'm having an issue with a simple animation using jQuery and the jQuery Easing plugin. The animations work fine, except when applied to section.quickReply Below is my HTML: <section class="post quickReply"> <form method="POST> ...