Trouble concealing tab using slideUp function in Jquery

Whenever I click on the 'a' tag, it displays additional HTML content (list) that is controlled by generic JS code for tabs. However, I want to hide the list when I click on the "Title" link again. What can I do to achieve this?

You can view a demo of what I have done so far.

JS

$(".nav_tab>ul>li>a").click(function(event) { 
    $(".nav_tab>ul>li>a").parent().removeClass("activo");
    $(this).parent().toggleClass("activo");

    var capa = $(this).prop('href').split('#');
    $(".nav_tabcontent").slideUp("fast");
    $("#"+capa[1]).slideDown("slow");

    event.preventDefault();
});

$(".nav_tab>ul>li>h3").click(function(event) { 
    $(".nav_tab>ul>li>a").parent().removeClass("activo");

    var o = $(this).parent().find("a");
    o.parent().toggleClass("activo");

    var capa = o.prop('href').split('#');   
    $(".nav_tabcontent").slideUp("fast");
    $("#"+capa[1]).slideToggle("slow");    

    event.preventDefault();
});

Answer №1

To implement the toggle class functionality in jQuery, you just need to use the toggle class method. Here is an example on JSFiddle: http://jsfiddle.net/d90ac70w/2/. Simply check if the div has a class of active.

$(".nav_tab>ul>li>h3").click(function (event) {
    $(".nav_tab>ul>li>a").parent().removeClass("activo");
    var o = $(this).parent().find("a");
    o.parent().toggleClass("activo");

    var capa = o.prop('href').split('#');

    if(!$("#" + capa[1]).hasClass('active')){
      $("#" + capa[1]).slideDown(); 
      $("#" + capa[1]).toggleClass('active'); 
    }else{
      $("#" + capa[1]).slideUp();   
      $("#" + capa[1]).toggleClass('active'); 
    }
    event.preventDefault();
});

As we are using the same jQuery selector repeatedly, we can simplify by chaining the methods together.

$(".nav_tab>ul>li>h3").click(function (event) {
    $(".nav_tab>ul>li>a").parent().removeClass("activo");
    var o = $(this).parent().find("a");
    o.parent().toggleClass("activo");

    var capa = o.prop('href').split('#');

    if(!$("#" + capa[1]).hasClass('active')){
      $("#" + capa[1]).slideDown().toggleClass('active');
    }else{
      $("#" + capa[1]).slideUp().toggleClass('active');
    }

    event.preventDefault();
});

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

Why am I seeing back-end console errors that are related to my front-end?

Recently, I encountered an error message that prevents me from using 'import' in my front end code when trying to execute 'node index'. This issue never occurred before, and it only arose when I returned to this project. In my backend ...

Only authenticated users are permitted to write to Firebase databases

Currently, I am in the process of setting up a new Vue JS project for a blog with Firebase integration. The main objective is to allow any logged-in user to create blog posts that are saved in the Firebase real-time database at https://xxx.firebaseio.com/b ...

Having trouble updating the value in the toolbar?

Here is an example that I added below: When I click the add button, the value of the "newarray" variable is updated but not reflected. I am unsure how to resolve this issue. This function is used to add new objects: export class AppComponent { ne ...

Iterate through each key in the response JSON object using a variable named "a

Here is a snippet of my code: var roomid= roomIds[i] const Availabilitydata = await AvailResponse.json(); availableroomsArray.push(Availabilitydata); app.get("/api/availability", (req, res) => { res.json({ indicateur: availableroomsA ...

PHP code to export data to a CSV file containing Chinese characters

I attempted the following: $name = iconv("utf-8", "GB18030", $value["name"]); Opening in a text editor and changing the encoding Importing into Excel while adjusting the encoding This process involves PHP and JavaScript: Here is my PHP code: echo & ...

A guide to customizing nested elements in react using styled-components

Currently, I am utilizing styled components to apply styles to a child element inside a div using nested css. For a demonstration, you can view my example here const customStyles = theme => ({ root: { ...theme.typography.button, background ...

Utilizing Datatables with mysqli for server-side processing through JSON

I'm encountering an issue with my implementation of datatables. Certain pages are crashing due to the large amount of data being fetched from the database. I attempted to resolve this by utilizing server-side processing. Despite following the examples ...

Get rid of the arrow that is displayed when using the `time` input type in HTML5

Recently, I encountered an issue with the default HTML5 code snippet. My custom background looked perfect except for a pesky black arrow appearing on the right side. In this image, you can see the problematic black arrow that needs to be removed. I attemp ...

`"Error: posts.map is not a function" - What steps can be taken to resolve this issue?`

While working on fetching data from my local Drupal instance in React JS, I encountered a situation where I needed to pass the data from Drupal using the JSON API module which sends the data in JSON format. You can view the JSON API data in the following i ...

Discovering the variable name that holds the maximum number following the usage of Math.max()

Let's assume we have the following variables set: var number1 = 48; var number2 = 420; var number3 = 39; If we want to determine the highest value among them, we can use: let maximumValue = Math.max(number1, number2, number3); What if we want to kno ...

What are the best practices for avoiding text wrapping around a DIV?

I have scoured this site extensively, searching for a solution to my problem. What I thought was a simple issue has left me frustrated after hours of trying to figure it out on my own. So, I've finally admitted defeat and turned to seek help... Here& ...

The Vite build tool creates unique CSS module classes for each component

Is it possible to set the CSS module class name in the index.js file generated during the Vite build process? I am developing with multiple themes and a single-entry JS file. Currently, this is the output I get when trying to build the project: Index.js & ...

Should the ListItem expand and collapse when clicked?

My react/material-ui component has the following structure: export const TodoItem: React.FC<Props> = ( {todo, itemKey}) => { const [dialogState, setDialogState] = React.useState<boolean>(false); const handleClose = () => { setDial ...

Create a unique filter in an ng-repeat directive that allows users to personalize the data displayed

Is there a way to create a custom filter that hides the inventory column for Color Pencil Special on October 2nd, 2017 in the view? The inventory for Color Pencil Special is dependent on the inventory of regular Color Pencils, which are stored somewhere e ...

splitting xmlhttp.responsetext using loops

Currently, I have a JavaScript function that utilizes xmlhttp.responsetext to fetch data from MySQL. This data is then used to populate form fields in a dropdown menu, which has been functioning perfectly so far. However, the issue arises when I attempt to ...

Sharing a Promise between Two Service Calls within Angular

Currently, I am making a service call to the backend to save an object and expecting a number to be returned via a promise. Here is how the call looks: saveTcTemplate(item: ITermsConditionsTemplate): ng.IPromise<number> { item.modifiedDa ...

Ensure the div remains fixed in its position regardless of the page's height

I am seeking assistance with making two divs of equal height on my website. The left div contains dynamic content that may expand vertically with various inner divs. Meanwhile, the right div has a single inner div that should remain visible at the top ev ...

Dividing the JSON dataset into smaller segments

Here is an example demonstrating how to split the JSON data: var data = [ { BankName: 'SBI', IFSC: 'SBIN0002688' }, { BankName: 'ICICI', IFSC: 'ICIC0003931', MICR: '500229094'}, { BankName: 'RBI ...

Switching the file format from HTML to .ASP resulted in the loss of the website's design elements and images

After initially creating an HTML file, I decided to rename it with a .asp extension for uploading online. To do this, I copied the original HTML file and moved it into a folder containing .asp files. However, after replacing the existing file, my website l ...

eliminating attributes from a JavaScript object

Seeking a method to strip object properties before sending them to the front-end. Why does this code work as intended: var obj = { name: 'cris', age: 22, } console.log(obj) //displays name and age delete obj.name console.log(obj) //dis ...