Expanding and collapsing DIV elements using JavaScript upon clicking navigation menu items

At present, the current code unfolds the DIVs whenever a user clicks on a menu item. This results in the DIV folding and unfolding the same number of times if clicked repeatedly on the same link, without staying closed.

My desired functionality is to have the DIV fold and remain closed when the user clicks on the same menu item for the second time, similar to how it works on a specific website.

Edit: To clarify:

Current behavior:

  • Clicking on a navigation menu link opens (unfolds) the associated DIV
  • Subsequent clicks on the same link hide (fold) the DIV temporarily before reopening it automatically

Desired behavior:

  • Clicking on a navigation menu link opens (unfolds) the associated DIV
  • A second click on the same link hides (folds) the DIV and keeps it that way until another click on the same link or a different menu item occurs

How can I implement this? Thank you

View http://jsfiddle.net/u3qtt6fo/5/

JS:

$("a").click(function() { 
    var page = $(this).data("page");
    var active = $(".fold.active");

    // if there is visible fold element on page (user already clicked at least once on link)
    if(active.length) {
      $(".fold.active")
      .animate({ width: "0" }, 200 )
      .animate({ height: "0" }, 200, function() {
      // this happens after above animations are complete
        $(this).removeClass("active")

        $("#"+page)
        .addClass("active")
        .animate({ height: "500px" }, 1000, 'linear' )
        .animate({ width: "500px" }, 400,'linear' )    


      })

    // clicking for the first time
    } else {  
      $("#"+page)
      .addClass("active")
      .animate({ height: "500px" }, 1000,'linear' )
      .animate({ width: "500px" }, 400,'linear' )

    }
});

HTML

<div id="fold1" class="fold">Div menu item 1</div>
<div id="fold2" class="fold">Div menu item 2</div>
<div id="fold3" class="fold">Div menu item 3</div>
<div id="fold4" class="fold">Div menu item 4</div>

<nav>
  <ul>
    <li><a href="#" data-page="fold1">Menu item 1</a></li>
    <li><a href="#" data-page="fold2">Menu item 2</a></li>
    <li><a href="#" data-page="fold3">Menu item 3</a></li>
    <li><a href="#" data-page="fold4">Menu item 4</a></li>
  </ul>
</nav>

CSS:

.fold {
    display: none;
    width: 0;
    height: 0;
}

.fold.active {
    display: inline-block;
}

#fold1 {
    border: solid 5px #bada55;
    background: red;
}

#fold2 {
    border: solid 5px #fed900;
    background: aqua;
}

#fold3 {
    border: solid 5px #223322;
    background: green;
}

#fold4 {
    border: solid 5px #55bada;
    background: purple;
}

ul {
    position: absolute;
    top: 50px;
    right: 50px;
    list-style-type: none;
}

Answer №1

Is this the solution you were looking for? Check it out here

I made some modifications to your code, specifically adding a jQuery selector "animated".

$("a").click(function () {
    var page = $(this).data("page");
    if ($('div:animated').id != page) {
        var active = $(".fold.active");

        // Check if there is already a visible fold element on the page
        if (active.length) {
            active.animate({
                width: "0"
            }, 200)
            .animate({
                height: "0"
            }, 200, function () {
                // Callback after animations are complete
                $(this).removeClass("active");
            })
        } else {
            $("#" + page)
                .addClass("active")
                .animate({
                    height: "500px"
                }, 1000, 'linear')
                .animate({
                    width: "500px"
                }, 400, 'linear')
        }
    }
});

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's prependTo method will add a display:block property to

Can't find a solution to this issue. This is the code snippet in question: var new_img = '<img id="' + drag_id + '" rel="' + drop_id + '" class="' + gallery_link + ' drop_out" src="' + drag_src + '" /& ...

How does CSS affect the size and performance of a website?

Examining the content of this css file (focusing on the last 5 lines specifically): #page section .s_1 { overflow:hidden; width:435px; float:left;} #page section .s_1 h1 { font-size:36pt; color:#001744; line-height:1.1; margin-bottom:64px;height:107px;} # ...

Are instance prototypes exhibiting static behavior?

I'm in the process of creating a game for Windows 8 using HTML/Javascript and WinJS, but I'm running into issues with "prototypes" acting statically when they shouldn't. This is my first time working extensively with Javascript and dealing w ...

Rearrange the order of divs dynamically to prevent wrapping/overflow, no need for media queries

Can someone help me with this issue? I am trying to create a navigation bar with centered menus/links, a logo on the left, and call-to-action buttons and icons on the right. If the content overflows or wraps, I want the center column to move to the next l ...

Customizing CSS for Various Browser Sizes

I have a query regarding window-dependent CSS. It seems to be a common issue, but I am facing some difficulties with it on Wordpress. I am currently using the script recommended by Nettuts. My goal is to apply different CSS styles based on the user's ...

Oops! The system encountered a problem: the property 'modalStack' is not recognized on the type 'NgxSmartModalService'. Maybe you meant to use '_modalStack' instead?

Currently, I'm facing an issue while attempting to run ng build --prod in my Angular 6 project. I have also incorporated the NgxSmartModal package for handling modals. Unfortunately, the build process is failing and I can't seem to figure out why ...

Need to `come back` multiple times

I am facing an issue where I want to return multiple lines, but only the first line is being returned. I attempted to create a function specifically for returning the line, but encountered errors because I couldn't figure out where to place it. Does ...

When a radio button is checked, add a class to its parent element that has a specific class assigned to it

In order to dynamically add a class to a specific div element higher up the DOM hierarchy when a radio button is clicked, I am in need of assistance. There are multiple instances of these div elements with different radio buttons, so it is crucial that on ...

Click event not functioning in programmatically loaded HTML

I am facing an issue with a JSON file that contains the page content I am trying to load. The link within it appears as follows: <a data-ng-click='foo()'>Bar</a> When I load this page content into the HTML page: <p class="body" ...

Execute a script upon page load

Is there a way to trigger a script tag <script> immediately upon the website loading? I've experimented with various codes, but haven't found one that meets my needs. ...

"Seeking assistance with concept sharing and content transmission. In need of guidance

Basic Question I'm stuck trying to brainstorm a concept to reach my objective. I am having trouble figuring out how to navigate the DOM correctly with my chosen method. The Objective First, let me explain what I am doing: I use ajax to bring HTML ...

Having trouble activating the Invalidate Cache function in rtk query with tags

Here is a snippet from my Api.js file: export const api = createApi({ reducerPath: 'api', baseQuery: fetchBaseQuery({ prepareHeaders: (headers, { getState }) => { const userInfo=JSON.parse(localStorage.getItem('userInfo' ...

What is the best approach for testing a component that makes use of React.cloneElement?

My main component fetches children using react-router in the following manner: class MainComponent extends Component { render() { return ( <div> {React.cloneElement(children, this.props.data)} </div> ) } } I a ...

Error encountered: Invalid symbol detected ('<') while attempting to parse JSON in an Angular application

I am experiencing an issue with my Angular code when trying to submit a form. Upon clicking the submit button, an error saying JSON Parse error: Unrecognized token '<' appears, and empty records are being saved in the database. I have included ...

Customize Monaco Editor: Implementing Read-Only Sections

I am currently working on setting up the Monaco Editor so that specific sections of the text content are read-only. Specifically, I want the first and last lines to be read-only. See example below: public something(someArgument) { // This line is read-onl ...

Error validation for jQuery div dropdown

Can jQuery validation be used to set the required attribute on a Bootstrap styled div dropdown instead of an option/select tag? The tags cannot be changed on this page, and there are multiple div dropdowns. <div class="btn-group"> <button typ ...

Retrieving entities from a text

I found a script on the Webdriver.io website that looks like this (adjusted for testing) const { remote } = require('webdriverio'); var assert = require('assert'); ;(async () => { const browser = await multiremote({ ...

Retrieving the HTML DOM element's value during a click event on a MapQuest map

My current project involves using MapQuest.Js to display a map. I need to retrieve the latitude and longitude coordinates when a user clicks on the map, along with the value of a radio button which is a DOM element. <link type=\"text/css\" re ...

Issue with non-responsive images in Bootstrap 3

Here is the bootstrap configuration that I am currently using: http://www.bootply.com/118172 I'm having an issue with the responsiveness of the image. It's not shrinking to match the height of the div on the left side. Can anyone help me trouble ...

Error encountered when attempting to initiate a second screenshare on Chrome due to an invalid state

I am interested in utilizing Screensharing in Chrome. After following a guide and creating an extension to access the deviceId for getUserMedia, I was able to successfully start streaming my screen. However, when I attempted to stop the stream using the pr ...