Using jQuery's slideToggle feature to hide content when clicked again or when a different button is

I have a challenge with creating toggle buttons that require specific functions:

1) Display content on the first click (this is working)

2) Conceal content when another button is clicked (this is also working)

3) Hide content on the second click (this is not working as intended)

Currently, clicking the same button twice causes the content to slide up and then immediately down, resulting in a jittery experience. Is there a solution to make all 3 functions work seamlessly? Removing the line "$(".assortiment").slideUp();" resolves the jumping issue but it interferes with function 2...

function assortiment(e){
  var assortimentid = e.id + "__js";
  if ($("#" + assortimentid).display = "block"){
    $(".assortiment").slideUp();
    $("#" + assortimentid).slideToggle();
  } else if ($("#" + assortimentid).display = "none"){
    $("#" + assortimentid).slideToggle();
  }
}
.assortiment {
  display: none;
 }
 
.btn {
  border: 1px solid black;
  border-radius: 10px;
  padding: 10px;
  width: 100px;
  margin: 5px;
  background-color: lightblue;
 }
 .btn:hover {
   cursor: pointer
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn" id="section1" onclick="assortiment(this)">Section 1</div>
  <div class="btn" id="section2" onclick="assortiment(this)">Section 2</div>
  <div class="btn" id="section3" onclick="assortiment(this)">Section 3</div>
  
  <div class="assortiment" id="section1__js">
    <p>SOME CONTENT 1</p>
    <p>Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum. Aliquip quaestio periculis ad eam, legere altera reprehendunt eu his. Cu has virtute pericula definitionem, cu facete conclusionemque has, cu errem accusamus duo.
</p>
  </div>
  <div class="assortiment" id="section2__js">
    <p>SOME CONTENT 2</p>
        <p>Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum. Aliquip quaestio periculis ad eam, legere altera reprehendunt eu his. Cu has virtute pericula definitionem, cu facete conclusionemque has, cu errem accusamus duo.
</p>
  </div>
  <div class="assortiment" id="section3__js">
    <p>SOME CONTENT 3</p>
        <p>Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum. Aliquip quaestio periculis ad eam, legere altera reprehendunt eu his. Cu has virtute pericula definitionem, cu facete conclusionemque has, cu errem accusamus duo.
</p>
  </div>

Answer №1

It's important to steer clear of inline javascript. Create a separate function for the click event on .btn elements to toggle the display. Use jQuery's slideToggle() method to toggle the same element, and slideUp() with not() to hide other elements.

Make sure to use strict comparison === instead of assignment = in conditions.

The statement element.display = "none" is invalid; it should be written as

element.css("display") === "none"
.

$(".btn").on("click", function() {
  var item = "#" + $(this).attr("id") + "__js"
  $(".assortiment").not(item).stop().slideUp();
  $(item).stop().slideToggle();
})
.assortiment {
  display: none;
}

.btn {
  border: 1px solid black;
  border-radius: 10px;
  padding: 10px;
  width: 100px;
  margin: 5px;
  background-color: lightblue;
}

.btn:hover {
  cursor: pointer
}

p {
  margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn" id="section1">Section 1</div>
<div class="btn" id="section2">Section 2</div>
<div class="btn" id="section3">Section 3</div>

<div class="assortiment" id="section1__js">
  <p>SOME CONTENT 1</p>
</div>
<div class="assortiment" id="section2__js">
  <p>SOME CONTENT 2</p>
</div>
<div class="assortiment" id="section3__js">
  <p>SOME CONTENT 3</p>
</div>

Answer №2

Make sure to include the .stop() method in your code to halt the animation currently running on the selected element, effectively preventing it from looping:

function assortment(e){
  var assortimentid = e.id + "__js";
  if ($("#" + assortimentid).display = "block"){
    $(".assortiment").stop().slideUp();
    $("#" + assortimentid).stop().slideToggle();
  } else if ($("#" + assortimentid).display = "none"){
    $("#" + assortimentid).stop().slideToggle();
  }
}
* {margin: 0; box-sizing: border-box} /* additional style for smoother layout */

.assortiment {
  display: none;
}

.btn {
  border: 1px solid black;
  border-radius: 10px;
  padding: 10px;
  width: 100px;
  margin: 5px;
  background-color: lightblue;
}

.btn:hover {
  cursor: pointer
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="btn" id="section1" onclick="assortment(this)">Section 1</div>
<div class="btn" id="section2" onclick="assortment(this)">Section 2</div>
<div class="btn" id="section3" onclick="assortment(this)">Section 3</div>

<div class="assortiment" id="section1__js">
  <p>SOME CONTENT 1</p>
</div>
<div class="assortiment" id="section2__js">
  <p>SOME CONTENT 2</p>
</div>
<div class="assortiment" id="section3__js">
  <p>SOME CONTENT 3</p>
</div>

Answer №3

Give this a shot

function displayItems(element){
  var itemId = element.id + "__js";
  if ($("#" + itemId).css("display") == "block"){
    $(".items").hide();
    $("#" + itemId).slideToggle();
  } else if ($("#" + itemId).css("display") == "none"){
    $("#" + itemId).slideToggle();
  }

Answer №4

Revamp your JavaScript function definition to :

function updateAssortiment(e){
  var assortimentid = e.id + "__js";
  $(".assortiment").not("#" + assortimentid).slideUp();
  $("#" + assortimentid).slideToggle(); 
}

Complete Snippet: and jsFiddle

function updateAssortiment(e){
  var assortimentid = e.id + "__js";
  $(".assortiment").not("#" + assortimentid).slideUp();
  $("#" + assortimentid).slideToggle(); 
}
.assortiment {
  display: none;
 }
 
.btn {
  border: 1px solid black;
  border-radius: 10px;
  padding: 10px;
  width: 100px;
  margin: 5px;
  background-color: lightblue;
 }
 .btn:hover {
   cursor: pointer
 }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn" id="section1" onclick="updateAssortiment(this)">Section 1</div>
  <div class="btn" id="section2" onclick="updateAssortiment(this)">Section 2</div>
  <div class="btn" id="section3" onclick="updateAssortiment(this)">Section 3</div>
  
  <div class="assortiment" id="section1__js">
    <p>SOME CONTENT 1</p>
    <p>Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum.</p>
  </div>
  <div class="assortiment" id="section2__js">
    <p>SOME CONTENT 2</p>
        <p>Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum.</p>
  </div>
  <div class="assortiment" id="section3__js">
    <p>SOME CONTENT 3</p>
        <p>Lorem ipsum dolor sit amet, aliquip apeirian dissentiunt ex pro. Ad choro facilis offendit mel, et quo quot democritum.</p>
  </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

Determining whether the selection in jQueryUI autocomplete was made using the ENTER key or not

Seeking assistance with implementing an autocomplete field using jQuery 1.7.2 and jQueryUI 1.8.12 to achieve the following: If a suggestion is chosen from the autocomplete list (via mouse or keyboard), execute function A If no matches are found (meaning ...

Persist the scroll position within a div even after refreshing a PHP file using AJAX

I have a specific div set up with its own scroll bar, which is being refreshed using AJAX (with a PHP file). Whenever I scroll within this div and trigger a reload, the inner scrollbar resets back to the top. My goal is to retain the position of the scroll ...

Switch out multiline text with javascript

Could someone assist me with this question? I am attempting to locate and replace specific code within a JavaScript file. The code is included in an AJAX response that contains a significant amount of HTML code. After retrieving the AJAX response, I stor ...

Responsive Div that Resizes Proportionally within Parent Container

Having a div element that adjusts its height based on width to maintain aspect ratio, I aim to place this div within another while maximizing available space vertically and horizontally without any cropping. It seems that object-fit: contain, typically use ...

What is the process for choosing with multiple attribute selectors?

Is there a way to disable multiple fields in a checkbox survey simultaneously? I attempted the following code, but it only works with one class. Is it possible to select by multiple classes within the same div? function surveyInit(){ $("div[class*=&apos ...

Strange CSS Problem: Button dysfunction in displays sized 13 inches or 15 inches

I have made a landing page using the latest version of bootstrap. However, I am encountering an odd issue where the success button is not clickable on certain devices such as 13-inch and 15-inch laptops and desktops. You can find the URL for the landing p ...

Ensuring Navigation Elements Remain Aligned in a Single Line

I'm in the process of developing an interactive project that will be showcased on a touch screen. One of its key features is a fixed footer navigation. Currently, I am using floats to position the main navigation elements and within each element, ther ...

Achieving vertical alignment of form controls with labels that wrap in a row using Bootstrap 4

I am facing an issue where input elements in a row with labels above them are causing alignment problems when the screen width is reduced. The longer labels wrap to the next line and push the input element down, increasing the overall height of the row: h ...

I am looking to utilize the data from a POST request to dynamically update the DOM through a script.js file. How can

After sending a post request, I am looking to update my database and then use an array to dynamically update the HTML content. However, I am struggling with how to pass this data to my script.js file. Here is my progress so far: SERVER let expenseAmo ...

The timing of the RequestAnimationFrame function varies based on the dimensions of my canvas

In my application, I have a canvas that dynamically adjusts its CSS size based on the window size. The main gameplay loop in my code looks like this: run = function(){ console.log(timerDiff(frameTime)); game.inputManage(); game.logics(); ...

Mandating the inclusion of a directives controller in conjunction with other necessary controllers

Two directives are nested within each other, with one requiring the other using require: '^parentTag' . Both directives have their own controllers. In the parent directive, I can access its controller as the fourth argument in link: function(scop ...

"Navigate back to a previous page in Vue Router without having to

I am currently exploring the option of creating a back button in my Vue.js application using vue-router that mimics the behavior of the browser's native back button. The challenge I'm facing is that when using history mode for the router and tryi ...

Create a visual representation of an item within a framework using an Angular directive

I am interested in using a directive to draw a triangle above a series of div elements. In my scenario, I have four squares and two values: charge and normal. The value of charge determines the color of the squares, while normal is used for drawing the t ...

Is there a method to delay HTTP requests until the number of pending requests drops below a certain threshold (N)?

I'm in the midst of a project that involves allowing users to upload multiple files simultaneously. However, sending out numerous requests all at once can overwhelm the server and trigger a 429 (Too Many Requests) error for those requests. Is there a ...

Issues with displaying errors in the delete confirmation box within Bootstrap 4

I am working on implementing a Bootstrap 4 modal confirmation before sending a delete request using JSON. Here is the code I have: $(document).ready(function() { $('.launchConfirm').on('click', function (e) { $('#confi ...

Getting the click event object data from a dynamically created button with jQuery or JavaScript

I have a task of tracking page button click events. Typically, I track the objects from statically created DOM elements using: $('input[type=button]').each(function () { $(this).bind('click', function () { ...

Saving a block of text to a database with PHP without the need to refresh the webpage

On my index.php page, I have a paragraph element and an input button: <p id="result">Hello this is test paragraph</p> <input id="insertbutton" type="button" value="insert" /> My goal is to save the paragraph content into a database ...

Is there a way to switch the language on the date-picker tool?

My date-picker has a unique set up: <input type="text" ng-readonly="true" class="form-control" datepicker-popup="yyyy-MM-dd" ng-model="filter.FInicial" is-open="filter.controlFInicialAbierto" min-date="minDateIni" max-date="maxDat ...

Retrieve a list of all file names within a designated directory using Angular

I am working on my Angular app and I need to list all the file names inside the assets folder. To achieve this, I am planning to utilize the npm library called list-files-in-dir https://www.npmjs.com/package/list-files-in-dir Here is the service impleme ...

How can I place an icon on a specific location in a Highcharts map?

I am currently utilizing Highcharts to showcase maps within my application. I am aiming to achieve two specific functionalities: 1) Upon clicking on any area, I want that area to be highlighted in red {completed} 2) Upon clicking on any area, I intend f ...