Toggle the display of items shown before without using the next() function

If you visit this website, you will notice that I am implementing a slideToggle function on various elements. To ensure that only one element is visible at a time, I have crafted the following code:

$(document).ready(function() {

  $( ".toggle" ).click(function() {

        if ($(this).next().is(":visible"))
            $(this).next().slideToggle("slow");
        else {
            $(".toggle").each(function() {
                if ($(this).next().is(":visible"))
                    $(this).next().slideToggle("slow");
            });
            var tog = $(this).attr("data-class");
            $("."+tog).slideToggle("slow");
        }
    });
});

I want to replicate this behavior with a carousel, but I'm struggling to hide previously toggled divs that are not adjacent to $(this). Here's what I've been trying to achieve:

    $( ".toggle2" ).click(function() {

      //Slide up if open
        if ($("."+tog).is(":visible"))
            $("."+tog).slideToggle("slow");
      //Slide up every visible
        else {
            $(".toggle2").each(function() {
                if ($("."+tog).next().is(":visible"))
                    $("."+tog).next().slideToggle("slow");
            });
      // slide Down
            var tog = $(this).attr("data-class");
            $("."+tog).slideToggle("slow");
        }
    });
.reszlet {
  display: none;
  background: #F9F9F9;
  border: 1px solid #D5D5D5;
  box-shadow: inset 0px 0px 5px 0px rgba(0, 0, 0, 0.18);
  padding: 15px 15px 10px 15px;
  margin-bottom: 30px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel">

          <div class="carousel-item item1">
            <div class="overlay">
              <h3>Ginappi youtube videók</h3>
              <button class="btn-light toggle2" data-class="munka1" type="button" >
                Részletek
              </button>
            </div>
          </div>

          <div class="carousel-item item2">
            <div class="overlay">
              <h3>Just nature</h3>
              <button class="btn-light toggle2" data-class="munka2" type="button" >
                Részletek
              </button>
            </div>
          </div>

          <div class="carousel-item item3">
            <div class="overlay">
              <h3>Nekem is lesz gyerekem!</h3>
              <button class="btn-light toggle2" data-class="munka3" type="button" >
                Részletek
              </button>
            </div>
          </div>

           <div class="carousel-item item4">
            <div class="overlay">
              <h3>Pelusfilm - Nyakig ülünk benne</h3>
              <button class="btn-light toggle2" data-class="munka4" type="button" >
                Részletek
              </button>
            </div>
          </div>


        </div>

        <div id="videos">
          <div id="ginappi" class="munka1 yt reszlet col-12" >
              <iframe width="100%" src="https://www.youtube.com/embed/kRoGnxw-tFI" frameborder="0" allowfullscreen></iframe>
          </div>

           <div id="nature" class="munka2 yt reszlet col-12"  >
            <iframe width="100%"  src="https://www.youtube.com/embed/nPu-v2kaG9g" frameborder="0" allowfullscreen></iframe>
          </div>

           <div id="gyerek" class="text-center yt munka3 reszlet col-12"  >
           <iframe width="100%"  src="https://www.youtube.com/embed/cpMIp0bDp6g" frameborder="0" allowfullscreen></iframe>
          </div>

          <div id="pelus" class="text-center yt munka4 reszlet col-12">
          <iframe width="100%"  src="https://www.youtube.com/embed/GXWt9hrvnJA" frameborder="0" allowfullscreen></iframe>
          </div>
        </div>

It appears that the previously shown items are not being hidden as intended.

Answer №1

To provide a unique identifier for the "actual/open" div, consider using a specific classname.

$(".toggle2").click(function() {
    var tog = $(this).attr("data-class");
    
    //Hide the current open element and remove its identifier
    $('.open').slideUp("slow").removeClass('open');
  
    //Display the new element and assign it the identifier
    $("." + tog).slideToggle("slow").addClass('open');
});
.reszlet {
  display: none;
  background: #F9F9F9;
  border: 1px solid #D5D5D5;
  box-shadow: inset 0px 0px 5px 0px rgba(0, 0, 0, 0.18);
  padding: 15px 15px 10px 15px;
  margin-bottom: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel">

  <div class="carousel-item item1">
    <div class="overlay">
      <h3>Ginappi youtube videók</h3>
      <button class="btn-light toggle2" data-class="munka1" type="button">
        Részletek
      </button>
    </div>
  </div>

  <div class="carousel-item item2">
    <div class="overlay">
      <h3>Just nature</h3>
      <button class="btn-light toggle2" data-class="munka2" type="button">
        Részletek
      </button>
    </div>
  </div>

  <div class="carousel-item item3">
    <div class="overlay">
      <h3>Nekem is lesz gyerekem!</h3>
      <button class="btn-light toggle2" data-class="munka3" type="button">
        Részletek
      </button>
    </div>
  </div>

  <div class="carousel-item item4">
    <div class="overlay">
      <h3>Pelusfilm - Nyakig ülünk benne</h3>
      <button class="btn-light toggle2" data-class="munka4" type="button">
        Részletek
      </button>
    </div>
  </div>


</div>

<div id="videos">
  <div id="ginappi" class="munka1 yt reszlet col-12">
    <iframe width="100%" src="https://www.youtube.com/embed/kRoGnxw-tFI" frameborder="0" allowfullscreen></iframe>
  </div>

  <div id="nature" class="munka2 yt reszlet col-12">
    <iframe width="100%" src="https://www.youtube.com/embed/nPu-v2kaG9g" frameborder="0" allowfullscreen></iframe>
  </div>

  <div id="gyerek" class="text-center yt munka3 reszlet col-12">
    <iframe width="100%" src="https://www.youtube.com/embed/cpMIp0bDp6g" frameborder="0" allowfullscreen></iframe>
  </div>

  <div id="pelus" class="text-center yt munka4 reszlet col-12">
    <iframe width="100%" src="https://www.youtube.com/embed/GXWt9hrvnJA" frameborder="0" allowfullscreen></iframe>
  </div>
</div>


Edit to address the comment

To verify if the item has the class open, use this method:

$(".toggle2").click(function() {
  var tog = $(this).attr("data-class");

  //Check if it's already open
  if (!$("." + tog).hasClass('open')) {
      //Hide the actual/open element and remove the identifier
      $('.open').slideUp("slow").removeClass('open');
      //Open the new element and assign the identifier
      $("." + tog).slideToggle("slow").addClass('open');
  }
});
.reszlet {
  display: none;
  background: #F9F9F9;
  border: 1px solid #D5D5D5;
  box-shadow: inset 0px 0px 5px 0px rgba(0, 0, 0, 0.18);
  padding: 15px 15px 10px 15px;
  margin-bottom: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="carousel">

  <div class="carousel-item item1">
    <div class="overlay">
      <h3>Ginappi youtube videók</h3>
      <button class="btn-light toggle2" data-class="munka1" type="button">
        Részletek
      </button>
    </div>
  </div>

  <div class="carousel-item item2">
    <div class="overlay">
      <h3>Just nature</h3>
      <button class="btn-light toggle2" data-class="munka2" type="button">
        Részletek
      </button>
    </div>
  </div>

  <div class="carousel-item item3">
    <div class="overlay">
      <h3>Nekem is lesz gyerekem!</h3>
      <button class="btn-light toggle2" data-class="munka3" type="button">
        Részletek
      </button>
    </div>
  </div>

  <div class="carousel-item item4">
    <div class="overlay">
      <h3>Pelusfilm - Nyakig ülünk benne</h3>
      <button class="btn-light toggle2" data-class="munka4" type="button">
        Részletek
      </button>
    </div>
  </div>


</div>

<div id="videos">
  <div id="ginappi" class="munka1 yt reszlet col-12">
    <iframe width="100%" src="https://www.youtube.com/embed/kRoGnxw-tFI" frameborder="0" allowfullscreen></iframe>
  </div>

  <div id="nature" class="munka2 yt reszlet col-12">
    <iframe width="100%" src="https://www.youtube.com/embed/nPu-v2kaG9g" frameborder="0" allowfullscreen></iframe>
  </div>

  <div id="gyerek" class="text-center yt munka3 reszlet col-12">
    <iframe width="100%" src="https://www.youtube.com/embed/cpMIp0bDp6g" frameborder="0" allowfullscreen></iframe>
  </div>

  <div id="pelus" class="text-center yt munka4 reszlet col-12">
    <iframe width="100%" src="https://www.youtube.com/embed/GXWt9hrvnJA" frameborder="0" allowfullscreen></iframe>
  </div>
</div>

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

Exploring Bootstrap: the ins and outs of customizing styles

How can one determine which bootstrap styles need to be overridden when customizing the appearance? Is there a trick to identifying where to set styles in order for them to take precedence over bootstrap styles? For instance, I've been struggling fo ...

Tips for customizing a red error input box in AngularJS when the cursor is present but no content has been entered

I am working on implementing validation in my form using AngularJS. My goal is to have the input box turn entirely red when there is an error. Currently, after I receive an error and delete the text with the cursor still inside the box, the color of the bo ...

The error code 413 payload too large was encountered when trying to process a base64 string in express,

I attempted to send a post request to my node server with a base64 encoded file. After encountering a PayloadTooLargeError: request entity too large exception, I decided to increase the payload limit using Express 4 convention: app.use(bodyParser.json({l ...

Guide to creating an ajax request between different sub-domains within the same website

Help needed! I am currently working with jquery, ajax and php, and I have created a function (PHP_FOLDER) that looks like this. function PHP_FOLDER(evt){ return "www.mywebsite.com/path/to/php/files/";} The main purpose of this function is to allow me to ...

Combining arrays by a shared property in JavaScript

My goal is to merge data from two arrays based on the userId. The current solution I have only works efficiently with small datasets, but it becomes impractical with larger arrays due to the excessive use of the filter method. Does anyone have a more effic ...

Troubleshooting ASP.NET MVC: Dealing with Null Values in Ajax Requests sent to

I'm having trouble transferring data from the view to the controller using Ajax. The data is arriving at the controller as null. I've tried various solutions, but nothing seems to work. Even adding a frombody attribute did not resolve the issue. ...

Create a table that allows one column to have ample space, while ensuring that the other columns have uniform widths

This HTML/CSS creation features the following: https://i.stack.imgur.com/R8PRB.png However, the challenge lies in making the Very Good, Good, Fair, Poor, Very Poor columns equal in width while still allowing the "question" column to adjust its width acco ...

Detecting Android devices

Issue: My website functions properly on desktop but has a problem with the carousel images skewing on iPhones. To address this, I created a separate CSS styling for iPhone devices and used a JavaScript function found online to detect iPhones and iPads. Un ...

Using select tags in conjunction with JavaScript can add dynamic functionality to your website

I've been working on adding dropdown menus to my website and have been using code similar to this: <select> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="opel">Opel</opti ...

Can you identify the animation being used on this button - is it CSS or JavaScript?

While browsing ThemeForest, I stumbled upon this theme: What caught my eye were the animation effects on the two buttons in the slider ("buy intense now" and "start a journey"). I tried to inspect the code using Firebug but couldn't figure it out com ...

Manipulating object attributes in three.js using WebGL

I'm currently working on animating a sphere with increasing radii. Below are the key parts of my code: function create_sphere(){ var sphereMaterial = new THREE.MeshLambertMaterial( { color: 0xCC0000 }); var radius=2,segments=50,rings=50; sph ...

Form confirmation popup with JQuery displaying input values upon submission click

Could anyone assist me with creating a form that displays a popup after submission, showing the entered values for confirmation along with edit and submit buttons? I have found several examples online, but none are exactly what I need. Your help would be ...

Is it possible to execute a server-side click on a div element?

I have a div with an image and name inside. How can I make this div trigger a server-side click event without changing its structure? Here is my code: <div class="tutorial" style="margin-left:5px;"> TUTORIAL<div class="firstico" style=" ...

Storing multiple textbox values in a single column in PHP

I am using JavaScript to show multiple text boxes when the add button is clicked, but I am unsure of how to store the values of these text boxes in a single column of a database table. Below is my form input code and JavaScript for adding a number of text ...

Generate images in real-time based on model element properties

I have a ViewModel that includes a collection of strings that I intend to use for dynamically displaying images on a Razor view. public List<string> States { get; set; } = new List<string>() { "ACT", "NSW", "NT", ...

The initial request does not include the cookie

My server.js file in the express application has the following code: var express = require('express'); var fallback = require('express-history-api-fallback'); var compress = require('compression'); var favicon = require(&apos ...

The dilemma with WordPress button hover effect in CSS

Looking for some help with CSS code to create a button that changes color on mouse-over, transitioning from: white background to black background black text to white text Any assistance would be greatly appreciated! Here is the CSS I have tried so ...

Safari not rendering SVG wave at full width reached

My SVG isn't scaling to 100% width in Safari like it is in IE, Chrome, and Firefox. Despite numerous attempts, I haven't been able to make my SVG stretch across the full width like it does in other browsers. The project is built using React. . ...

Stacked divs needed to be aligned vertically

Is there a way to make the head and main tabs fixed vertically one below the other? Keep in mind that these need to be separate angular components and cannot be combined under another div. The rows also need to be scrollable. .pages { float: left; ...

Is there a way to attach a canvas image to an email using VB.NET?

In my project, I have successfully converted an SVG to a canvas image using canvg, then converted it to a bytearray in vb.net on the client side. I saved the image to a folder on my server in order to attach it to an email: Protected Sub Button1_Clic ...