Is there a way to make the div visible with just one click instead of two?

var sections = ["intro", "content"];
var visibleSectionId = null;

function toggleVisibility(sectionId) {
    if (visibleSectionId == sectionId) {
        visibleSectionId = null;
    } else {
        visibleSectionId = sectionId;
    }
    hideInvisibleSections();
}

function hideInvisibleSections() {
    var i, sectionId, section;
    for (i = 0; i < sections.length; i++)
    {
        sectionId = sections[i];
        section = "#" + document.getElementById(sectionId).id;
        if (visibleSectionId == sectionId) 
            $(section).fadeIn();
        else 
            $(section).fadeOut();
    }
}

Initially, it works correctly. However, when attempting to re-open the same section after closing it by clicking on an element, it requires two clicks. This behavior is due to the functionality where the visibleSectionId is reset to null upon first click and then fadeOut occurs on the second click since it no longer matches the selected section id.

I understand the issue at hand, but I am unsure about how to address it effectively.

Answer №1

There is no need for an additional function in this case. By storing the visible div ID in "visibleDivId", you can simply hide that particular div instead of cycling through all other divs.

var divElements = ["navMenu", "sidebar"];
var currentVisibleDiv = null;

function toggleVisibility(divIdentifier) {
    if (currentVisibleDiv == divIdentifier) {
        $(currentVisibleDiv).fadeOut();
        currentVisibleDiv = null;
    } else {
        if (currentVisibleDiv) {
            $(currentVisibleDiv).fadeOut();
        }
        currentVisibleDiv = divIdentifier;
        $(currentVisibleDiv).fadeIn();
    }
}

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

Error encountered when attempting to save a video using PHP due to an undefined index

Seeking assistance with my php code dilemma. I am attempting to insert data into mysql using a form that includes a video upload option which stores the video locally and the video URL in the database. However, when testing the form, I encounter multiple e ...

Preventing JQuery from interrupting asynchronous initialization

I am currently developing an AngularJS service for a SignalR hub. Below is the factory code for my service: .factory('gameManager', [function () { $.connection.hub.start(); var manager = $.connection.gameManager; return ...

I recently designed a form using a combination of HTML and JavaScript in order to display different dialogues depending on the number of selections made. Unfortunately, the alert function does not seem to be functioning

The concept is to have users select options and then receive employment sector suggestions based on their selections. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...

Executing a webservice method in an html page using javascript without the need to refresh the page

Is it possible to call a webservice from an index.html page using JavaScript? My webservice is located at "localhost/ws/service.asmx" and the specific web method I want to call is called HelloWorld. The index.html page contains an HTML submit button whic ...

Effortless scrolling on specific div elements, rather than the entire body

Currently, I am utilizing the following code to achieve smooth scrolling for links: function filterPath(string) { return string .replace(/^\//,'') .replace(/(index|default).[a-zA-Z]{3,4}$/,'') .replace( ...

I am looking to transform my string code into a PDF file using an ASP.NET MVC controller by passing the string through an AJAX call to the controller

Currently, I am attempting to change an HTML string into a PDF format using iron PDF within the asp.net-mvc environment. However, since it is only a trial version, could you provide me with an alternative solution to converting an HTML string to a PDF in ...

Retrieval of request in iframe URL

Currently, a third party is displaying my URL within their iframe. They are limited in flexibility and simply hard code the URL I provide them with. <iframe url="https://firstURL.com"></iframe> Now, I need to distinguish between two groups of ...

Encountering an error while configuring webpack with ReactJS: Unexpected token found while

I'm attempting to update the state of all elements within an array in ReactJS, as illustrated below. As a newbie to this application development, it's challenging for me to identify the mistake in my code. closeState(){ this.state.itemList.f ...

Activate dark mode automatically in material-ui

According to the official documentation: The documentation mentions that a dark mode theme will be automatically generated and reflected in the UI, but I am encountering issues with it. Dependencies: "@emotion/styled": "^11.0.0", ...

Organize data in a table using a dropdown selection menu

My data structure looks like this: $scope.friends = [ { name:'John', phone:'555-1212', age:10 }, { name:'Mary', phone:'555-9876', age:19 }, { name:'Mike', phone:'555-4321', age:21 }, { na ...

What is the best way to make a div span the entire height of the body?

I have a menu that I want to wrap inside a yellow div. The yellow div should take up the entire height of the green square, regardless of the content size in the green square. For example, if the orange square expands, the yellow div should also expand. h ...

Is it necessary to bump the major version if I make updates to a react module that does not affect existing code functionality, but may cause Jest snapshot tests to break?

Imagine I am developing a module for a react component and currently working on a PR to introduce a new feature. Along with this new feature, I have also made changes to the component by refactoring it to eliminate certain internal parts that were previou ...

Exporting all components using require: A complete guide

Currently, I am working on a Vue js application where I am tasked with exporting all the files and components from a specific directory. These files/components need to be imported into a separate file named paths.js. If I use the require function to impor ...

Tips for preventing redirection in Vue 3 composition API with asynchronous requests

I have successfully configured a submission form to send data to my email and add it to a Google sheet using the method described in this GitHub link. The process worked seamlessly for both purposes. However, I am facing an issue where upon submitting the ...

Trouble with jQuery script causing initial word count issue in textarea upon page load

I have implemented a word count textarea jQuery script and I am trying to figure out how to update the word count onload to 2 when the text area initially displays "this example". Currently, it shows 0 words. Although I can set focus on it and move the c ...

utilizing callback function for creating shopping cart feature within React

I'm in the process of creating an ecommerce website and implementing the add to cart functionality. I'm facing an issue where passing a callback function using props from a component to the parent component isn't working as expected. I' ...

Sending data to my jQuery Mobile application

$.ajax({url: 'myurl', {data:{parameters : params}}, success: function(result){ $("#container").html(result); } }); When trying to pass the parameters as shown above, I am getting a null value back when acce ...

The measurement of a HTML window's entire content height (not just the visible viewport height)

Currently, I am attempting to determine the total height of a webpage's content, not just what is visible. In my efforts, I have managed to achieve some success in FireFox using: document.getElementsByTagName('html')[0].offsetHeight. Howeve ...

challenge with filling and overflowing in Microsoft Edge

Here is a snippet of generic CSS (SCSS) style for flex: .flex { display: flex; &.v { flex-direction: column; } &.h { flex-direction: row; } > * { flex: 0 0 auto; } > .fill { flex: 1 1 auto; } &am ...

After implementing the ng-repeat directive, the div element vanishes

I've been working on fetching data from a Json API and displaying it on user event. However, I'm facing an issue where the div disappears whenever I apply the ng-repeat property to it. Despite searching through various tutorials and documentation ...