jQuery - Reveal one div while concealing another

I've been working on a script to toggle between two divs onClick - opening one while closing the other if it's already open. I'm fairly new to jQuery and Javascript, having mainly worked with HTML/CSS.

Script I found:

http://jsfiddle.net/J9vdr/1/

$(document).ready(function () {
    var expanded = false;
    var collapsed = true;
    $(".expanderHead").click(function () {
        if (expanded == true) {
            expanded = false;
            collapsed = true;
        } else {
            expanded = true;
            collapsed = false;
        }

        if (expanded == true) {
            $(".expanderSign").html("-");
            $(".expanderContent").slideToggle();
        }

        if (collapsed == true) {
            $(".expanderSign").html("+");
            $(".expanderContent").slideToggle();
        }
    });
});

My attempt:

http://jsfiddle.net/YqEVZ/2/

$(document).ready(function () {
    var expanded = false;
    var collapsed = true;
    $(".infoexpanderHead1").click(function () {
        if (expanded == true) {
            expanded = false;
            collapsed = true;
        } else {
            expanded = true;
            collapsed = false;
        }

        if (expanded == true) {
            $(".infoexpanderSign1").html("-");
            $(".infoexpanderContent1").slideToggle();
            $(".infoexpanderContent2").slideToggle();
        }

        if (collapsed == true) {
            $(".infoexpanderSign1").html("+");
            $(".infoexpanderContent1").slideToggle();
            $(".infoexpanderContent1").slideToggle();
        }
    });

    $(document).ready(function () {
        var expanded = true;
        var collapsed = true;
        $(".infoexpanderHead2").click(function () {
            if (expanded == true) {
                expanded = false;
                collapsed = true;
            } else {
                expanded = true;
                collapsed = false;
            }

            if (expanded == true) {
                $(".infoexpanderSign2").html("-");
                $(".infoexpanderContent2").slideToggle();

            }

            if (collapsed == true) {
                $(".infoexpanderSign2").html("+");
                $(".infoexpanderContent2").slideToggle();
            }
        });
    });

The goal is to have different content in each infoexpandercontent. When 'Content 1' is expanded, 'Content 2' should collapse. Is there a way to add a CSS class to the 'expanded' span for a smoother transition?

If you need more clarity or have any suggestions, please let me know!

Thank you for any help!

Answer №1

If you want to have one of them visible by default, you can condense everything down to these few lines:

$(document).ready(function () {
    $(".infoexpanderHead1, .infoexpanderHead2").click(function () {
        $(".infoexpanderContent1,.infoexpanderContent2").slideToggle();
        $(".infoexpanderSign1, .infoexpanerSign2").each(function() {
            $(this).html($(this).html() == '-' ? '+' : '-');
        });
    });
});

jsfiddle

A possible issue in your code is the use of uncommon classes between 2 sets of elements. By updating your layout, you can make it more dynamic like this:

<div class="infoExpander expanded">
    <div class="head"><span class="sign">-</span>Lorem ipsum</div>
    <div class="content">Lorem ipsum<br />Lorem ipsum</div>
</div>
<div class="infoExpander">
    <div class="head"><span class="sign">+</span>Lorem ipsum</div>
    <div class="content">Lorem ipsum<br />Lorem ipsum</div>
</div>

Adjust your JS as follows:

$(document).ready(function () {
$(".infoExpander .head").click(function () {
    $('.content').not($(this).nextAll('.content')).slideUp().prevAll('.head').find('.sign').html('+');
    $(this).nextAll('.content').slideDown(function() {
      $(this).closest('.infoExpander').addClass('expanded').find('.sign').html('-');
    });
});
});

Check out this jsfiddle to see it in action.

Answer №2

Ensure that the content is contained within the parent element. I have provided a small demonstration here: http://jsfiddle.net/F8Ean/

Eliminate the "1" or "2" in the class name, as the class names should be consistent. Consider using IDs for unique identifiers and classes for shared ones. Find all elements with the class .infoexpanderHead, and add a click event to toggle the visibility of the .infoexpanderContent within itself.

The siblings() function targets all elements with the same class as the clicked element on the same level (.infoexpanderHead).

$('.infoexpanderHead').click(function(){
    $(this).siblings().find('.infoexpanderContent').slideUp();
    $(this).find('.infoexpanderContent').slideDown();
});

By implementing this approach, you can easily add multiple blocks while ensuring that the code handles all elements accordingly.

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

Encountering a challenge in Angular 8: Unable to locate a supporting object matching '[object Object]'

I am having an issue trying to retrieve the Spotify API from the current user's playlists. While I can see it in my console, when I attempt to insert it into HTML, I encounter the following error: ERROR Error: Cannot find a differ supporting object ...

Setting the height of a child div: A step-by-step guide

Within a nested div with a height of 48px and positioned relatively, there is another child div also with a height of 48px. The goal is to set the maximum height of the child div to 80% and the minimum height to 40%. However, even after applying these sett ...

Developing a versatile table component for integration

My frontend app heavily utilizes tables in its components, so I decided to create a generic component for tables. Initially, I defined a model for each cell within the table: export class MemberTable { public content: string; public type: string; // ...

Why does my jQuery.get() callback function not execute?

After implementing the code below, I expected to see 'hi mom' displayed between the <div id='job-status'></div> on the original page. However, the result is not as anticipated: $(function () { function show_status() { ...

What is the best way to create a dynamic pie chart in AngularJS using JSON data?

In my controller: When calling the web services, if the service is successful, then retrieve the data and push it into the corresponding arrays. for(var i = 0; i < $scope.reportRangeList.length; i++) { count++; if( ...

When using JQuery Validation on a small screen, error messages can cause the button to shift downwards

After successfully creating an email form with jquery validation error style that appears when there's an error, I encountered a problem. When the screen width is reduced or viewed on a small screen, the error message pushes down the button. I&apos ...

The CSS selector for adjacent siblings seems to be malfunctioning

This code is designed to show the "container-1" division every time I hover over the "container" division. However, it's not behaving as expected because instead of displaying block on hover, it simply remains hidden. CSS Code .container:hover + .con ...

Utilizing the document.createDocumentFragment() method along with innerHTML for manipulating a Document Object Model (

I am currently in the process of creating a document fragment using the code below: let fullHTMLDocument = '<!doctype html> <html><head></head><body><h1>hello world</h1></body></html>'; let f ...

The webpage is drifting sideways to the right without any content being displayed

Recently, I launched a new website and encountered an issue with a static page I designed. While it may not be a critical problem, it is certainly bothering me! If you want to check out the website in question, visit: In essence, I have used CSS to hide ...

Is it advisable to utilize $locationProvider in AngularJS version 1.3.14?

Attempting to utilize html5Mode to remove # from the url in SPAs resulted in an error when using $locationProvider in AngularJS v 1.3.14. The reason for this error is unclear. The code snippet and console error are provided below for reference. Front End: ...

What is the method for transforming a JavaScript array (without an object name) into JSON format (with an object name)?

Currently, I am using an ajax query to read a local csv file and then loading the extracted values into an array. This is how the string value appears in the csv file: "Tiger","Architect","800","DRP","5421" ...

Responsive center alignment of stacked `<div>` elements using CSS

My goal is to center a stack of divs in 3 columns per row if the browser window is wider than 1024px, and switch to 2 columns per row if it's smaller, while still displaying all 6 divs. Unfortunately, I'm facing difficulties trying to apply what ...

React - triggering a router link action before the link is assigned a value

In this scenario, the issue arises because the URL changes before the link receives a value. The state is being received directly through the component but by the time it happens, the component has already been clicked. This results in the value being as ...

PHP - The form page freezes up every time I try to submit the form

Hey there! I've encountered an issue with my form submission. Everything works perfectly fine, except when the Title field is left blank. Here's a snippet of my HTML code: Title: <input type="text" name="title"><br /> Description:&l ...

Every time I try to store the response text from a jQuery ajax call in a variable, it

Seeking assistance from the knowledgeable individuals on this platform. I'm encountering difficulties in assigning a variable to the response text of a jQuery ajax call. My form triggers the "checkemail" function upon submission to verify if the ente ...

Formik button starts off with enabled state at the beginning

My current setup involves using Formik validation to disable a button if the validation schema is not met, specifically for a phone number input where typing alphabets results in the button being disabled. However, I encountered an issue where initially, ...

Modify the Markdown blockquote HTML format in Jekyll

Currently, I am diving into the world of Jekyll and I am working with a basic file that includes YAML frontmatter like this: --- layout: 'post' --- > Test Quote One accomplishment I'm proud of is successfully linking my CSS stylesheet t ...

Issue with MomentJS inBetween function consistently displaying incorrect results

I'm currently working on Vue Datatable and I have a specific requirement to search for records between two dates. I am using the moment.js library and the inBetween function to achieve this. Strangely, when I hardcode the dates, the function returns t ...

Loop variables undergoing change

I am currently working on a loop that fetches data from an API and then processes it to populate a simple array with the retrieved information. Promise.all(promises.map(obj => API.functionName(obj))).then((response) => { var index = startingDate; ...

Error received when attempting AJAX call with jQuery 1.7.2: NS_ERROR_XPC_NOT_ENOUGH_ARGS

Encountering an issue with jQuery version 1.7.2 and the ajax function. When running the code snippet below, Firefox Firebug console displays the following error: NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace] var wei ...