Is there a way to smoothly toggle a class using fadeToggle in jQuery?

Currently, I'm utilizing the fadeToggle() function to switch between the visibility of selected elements. Upon page load, all elements in question are assigned the 'invisible' class (which applies the CSS property display: none;).

I aim to toggle this class name to enable another function that also toggles the visibility of said elements by targeting those with the invisible property.

This is the existing code snippet for reference:

  var sections = $('.ovelseSeksjon');
  var title = sections.find("h1")
  var assignments = sections.find(".ovelseInnhold");
  var plusMinus = sections.find(".fa");
  var toggleAll = $("#mainText").find(".toggleall");

  // Initially hide all assignments on page load
  assignments.addClass("invisible");

  // Toggle the invisible class upon clicking the title
  title.on('click', function() {
    $(this).parent().find(".invisible").fadeToggle("fast", "linear");
  });

  toggleAll.on("click", function() {
    if($(this).hasClass("open")) {
      assignments.filter(".invisible").removeClass("invisible");
    }
    if($(this).hasClass("close")) {
      assignments.not(".invisible").addClass("invisible");
    }
  });

The current implementation partially achieves the desired effect. However, it only adds a new style property display: block, without completely removing the invisible class. Is there a solution to entirely eliminate the invisible class or enhance the toggleAll functionality to work as intended? (It shouldn't solely hide the elements; even after removing the invisible property, the display: block remains unaffected by toggleAll).

Your insights are much appreciated!

Answer №1

It may not be the perfect HTML hierarchy for your needs, but here is an example to consider.

Your task content (.ovelseInnhold) should initially have display:none set using CSS.

var sections = $('.ovelseSeksjon');
  var title = sections.find("h1")
  var assignments = sections.find(".ovelseInnhold");
  var plusMinus = sections.find(".fa");
  var toggleAll = $("#mainText").find(".toggleall");


  // Toggle visibility when the title is clicked
  title.on('click', function() {
    // To ensure correct scope, something different will happen in setTimeout.
    $(this).parent().find(".ovelseInnhold").fadeToggle("fast", "linear");
  });

  toggleAll.on("click", function() {
    $('.ovelseInnhold').fadeToggle("fast", "linear");
  });
.ovelseInnhold { 
  display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="mainText">
  <div class="toggleall">Toggle All</div>
</div>


<section class="ovelseSeksjon">
  <h1>Title 1</h1>
  <div class="ovelseInnhold">
    Assignments
  </div>
</section>


<section class="ovelseSeksjon">
  <h1>Title 2</h1>
  <div class="ovelseInnhold">
    Assignments
  </div>
</section>

Answer №2

I began working on the HTML code before your post, so please keep that in mind. The specifics are explained in the Snippet section.

SNIPPET

var txt = $('#mainText');
var sec = $('.section');
var hdr = $("h1");
var sub = $(".subSection");
var ico = $(".fa");
var all = $(".toggleAll");

sub.addClass("inv");

// Click a title to...
hdr.on('click', function() {
  
  /*
  |Select this title's siblings that follow afterwards
  |and switch their class between .inv and .vis
  */
  $(this).nextAll(sub).toggleClass('inv vis');
});

// Click the .toggleAll button...
all.on("click", function(e) {
  
  // Prevents anchor from jumping
  e.preventDefault();
  
  // Switch between plus and minus icons
  ico.toggleClass('fa-plus fa-minus');
  
  //Switch `.toggleAll` classes
  $(this).toggleClass('close open');
  
  // if this button ends up with class .close...
  if ($(this).hasClass('close')) {
    
    // remove/add = classes .vis and .inv
    sub.removeClass('vis').addClass('inv');
  } 
  else {
    
    // else vice versa
    sub.removeClass('inv').addClass('vis');
  }
});
html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
  background: #999;
}
.vis {
  display: block;
  opacity: 1;
  line-height: 1;
  width: 100%;
  transition: all 500 linear;
  color: white;
  background: black;
}
.inv {
  display: none;
  opacity: 0;
  line-height: 0;
  width: 0;
  transition: all 500 linear;
}
.close {
  background: black;
  color: yellow;
  line-height: 0;
  transition: all 1s ease-in;
}
.open {
  background: yellow;
  color: black;
  line-height: 3;
  transition: all 1s ease-out;
}
h1,
section {
  cursor: pointer;
  background: rgba(0, 0, 0, .3);
}
.toggleAll {
  width: 100%;
  padding: 15px 5px 0;
}
<link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<main id='mainText'>
  <a href='#/' class='toggleAll close'>
    <i class='fa fa-plus fa-2x'>ALL</i>
  </a>
  <section class='section'>
    <h1>I to IV</h1>
    <div class='subSection'>ONE</div>
    <div class='subSection'>TWO</div>
    <div class='subSection'>THREE</div>
    <div class='subSection'>FOUR</div>
  </section>
  <section class='section'>
    <h1>V to VIII</h1>
    <div class='subSection'>FIVE</div>
    <div class='subSection'>SIX</div>
    <div class='subSection'>SEVEN</div>
    <div class='subSection'>EIGHT</div>
  </section>
  <section class='section'>
    <h1>IX to XII</h1>
    <div class='subSection'>NINE</div>
    <div class='subSection'>TEN</div>
    <div class='subSection'>ELEVEN</div>
    <div class='subSection'>TWELVE</div>
  </section>
</main>

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

Activate a button upon the user clicking the Enter key

Is there a way to automatically trigger a button click when the user presses the Enter key inside an input field? I've attempted to achieve this functionality, but have been unsuccessful so far. Here is my code snippet: <!DOCTYPE htm ...

Use jQuery to compare the input values whenever they are modified

I am trying to synchronize the input values of two inputs as they are typed in. The code I have seems to work sometimes, but not consistently. Here is the code snippet: $('#google-querynav').keypress(function() { var text = $(this).val(); ...

The chosen choice is not able to be shown within the option tag

When attempting to filter options using JavaScript based on a selected item, I'm encountering issues. If the selected element contains 'CONTINUE' or 'BRACKET', it should be split into an array by space and only the first two indice ...

VSCode is indicating a CSS error, requesting an at-rule or selector

I tried to implement a piece of CSS code I found on a website, but I'm encountering an error in this particular section .pricing-table:hover{ box-shadow: 0px 0px 19px -3px rgba(0,0,0,0.36); /*issue starts from this line*/ .pricing-table__button ...

Ways to automatically divide lists into various div elements

Hey there! I currently have a list of categories on my page that is subject to change. I'm looking for assistance in creating a loop that will divide my lists into groups of 5 items per div. For example: foreach($categories as $cat) <label> ...

Attempting to change the primary color in Bootstrap is ineffective following a button click

I have been attempting to customize the primary color of Bootstrap 5 using SCSS. Everything works perfectly until I click a button that opens an external link. Below is the content of my SCSS file: $primary: #ae217aff; @import "../node_modules/boots ...

What is the location where UIWebView saves HTML5 offline files?

I'm curious about the location where HTML5 offline content is stored when saved from a UIWebView in an iOS app. Is it saved locally within my app's access, or somewhere else? ...

Tips for increasing the size of Material-ui Rating icons

I am currently utilizing npm to develop a widget. I aim to utilize the material-ui Rating component and have successfully integrated it. However, when I embed the widget on a webpage, the html font-size is set at 62.5%, causing the component to appear too ...

Preventing a particular CSS file from being applied to my Angular component

Currently, my modal component is built using bootstrap, but we encountered an issue with our project's CSS file which also utilizes the same classes as bootstrap (.Modal, .Modal-header). This conflicting styling was causing problems for the design of ...

How can I retrieve a text file using an API in a Next.js application?

Is there a way to download a text file using an API in Next.js? The console.log(ninjas) function is already displaying the correct information. I have tested the API with Postman and it works perfectly. When I use GET in Postman, the same information is ...

The registration page in PHP is malfunctioning, and the reason remains a mystery to me

Having trouble with my register page submit button. Any help is appreciated. Below is the structure of my SQL table: CREATE TABLE `USERS` ( `id` int(20) NOT NULL AUTO_INCREMENT PRIMARY KEY, `username` varchar(50) NOT NULL, `password` varchar(50) N ...

Include Item and remain on the same webpage - utilizing PHP, AJAX, and jQuery

Using google translator may result in errors. The issue I'm facing: adding an item and remaining on the current page I attempted to follow the advice provided in the following link but unfortunately, I was unsuccessful :-( Add Item and stay in curr ...

The tablesort feature is experiencing difficulty sorting tables with dynamically changing content

I have a question about sorting columns in a PHP file that calls a JS file. The PHP file contains two tables with the table sorter plugin implemented, but one of them works and the other doesn't. The working table is populated through an Ajax call, wh ...

Discovering the worth of a key within a JSON file

Below is a JSON with objects containing artist and image values. I need a function that, given an artist name, will return the corresponding image value in the same object. All objects are enclosed in an array as a JSON. var iTunes_data = $([{ "titl ...

splitting lengthy words into several lines

Does anyone know how to break words like the examples below using CSS or jQuery? SAMPLE 1 ConfigTechnologyHormonyAppComponentBackOfficeLaunch It needs to be broken into ConfigTechnologyHo rmonyAppComponentB ackOfficeLaunch SAMPLE 2 WorkAppComponentBa ...

What is the best way to transmit several data fields to a PHP page using Ajax?

Having an issue where I need to send 2 posts to my author PHP page using AJAX. Here's my original code: $.ajax({ type: "POST", url: "includes/get_competitions.php", data:'sport=<?php echo $_GET['sports']; ?>', success: func ...

"The distinctive sound of an Internet Explorer click paired with the power

Is it possible to prevent the click sound in Internet Explorer that occurs when submitting a form using jQuery? ...

"Taking a break" and indulging in Sass

When transferring Sass classes from another project, I wanted to create a wrapper to contain these styles locally. Here is how my wrapper is currently set up: .my-wrapper { @include "framework-main" } Initially, everything seemed fine. However, I soo ...

Determine the total value of various dynamic elements by utilizing jQuery/Javascript for calculation

I am currently working on a project that involves a dynamic list of products in a cart. I need to calculate the total price of all the products in the cart, but I am having trouble figuring out how to access and calculate the values from these dynamic elem ...

What is the process for determining the destination of my form data in HTML?

I recently created a form for my website, but I'm unsure of how to set it up so that the information submitted goes somewhere. After scouring various forums, it seems like I need to generate a PHP page. Can someone provide me with tips on how to get s ...