Using JQuery toggle to toggle between multiple divs with icons

I have been exploring ways to use a selectors for expanding and collapsing multiple divs, but haven't found an example that includes switching icons depending on the collapse/expand state.

Is there a way to modify the code below so that it allows me to expand and collapse multiple divs independently? For instance, opening one should not automatically open all others.

<!-- HTML -->
<a href="#" class="show_hide">Show</a>

<div class="slidingDiv" style="display: block;">
Check out
</div>

<!-- CSS -->
.show_hide{
  background:url(http://img37.imageshack.us/img37/1127/plusminus.png) no-repeat;
  padding-left:20px;  
}

<!-- JS -->
$(document).ready(function(){


  $(".slidingDiv").hide();

    $('.show_hide').click(function(){
        $(this).next(".slidingDiv").slideToggle();
      var isShow = $(this).text() == 'Show';
      $(this).text(isShow ? 'Hide' : 'Show').css({backgroundPosition:'0 '+ (isShow?-18:0) +'px'});
    });

});

Answer №1

If you need a more intricate solution, here are some suggestions:

1 - Utilize different icons for hide/show functionality:

Assign distinct classes for showing and hiding elements, then use removeClass & addClass to modify your "a" class. For example:

$('a.group1').removeClass('hiding').addClass('showing');

2 - Prevent hiding/showing multiple divs by using an additional class for grouping them together.

For instance:

<a class="show_hide group1">
<div class="slidingDiv group1"> div1 </div>
<div class="slidingDiv group1"> div2 </div>

...

$('.slidingDiv.group1').hide();

This way, you can target them using "a.group1" and ".slidingDiv.group1"... Where slidingDiv controls the visibility, and group1 determines what should be hidden or shown.

Check out these resources:

Answer №2

  $(document).ready(function(){
 $(".show_hide").click(function(){
$("div").slideToggle();
 });
});

Here is a helpful resource for you to check out:

  http://jsfiddle.net/ABC123/XYZ456/

You can refer to this example jsfiddle for further guidance.

Answer №3

If you're in search of a solution, look no further than an accordion. Try searching for "jQuery Accordion" and you'll discover numerous options available.

Here's a simple starting point if you prefer to tackle it yourself:

HTML:

<div id="container">
    <div class="header">H1</div>
    <div class="content">c1</div>
    <div class="header">H2</div>
    <div class="content">c2</div>
    <div class="header">H3</div>
    <div class="content">c3</div>
</div>

CSS:

.container { height: 600px; width: 400px; }
.header { height: 32px; background: url(plus.png) no-repeat right center; }
.selectedHeader { background: url(minus.png) no-repeat right center !important; }
.content { height: 200px; }

Javascript:

$('#container').live("click", function (e) {
    var $item = $(e.target);
    if ($item.hasClass("header")) {
        $item.addClass("selectedHeader").siblings().removeClass("selectedHeader"));
        $content.not($item.next()).slideUp();
        $item.next().slideDown(UxSpeed);
    }
}

// this will hide all contents initially and show only the first one
$('.header').not($('.header').first()).next().hide();

I hope this information is beneficial to you.

Answer №4

Opt for using slideToggle with $(this) rather than utilizing it with $(".slidingDiv")

$(document).ready(function(){
    $(".slidingDiv").hide();    
    $('.show_hide').click(function(){           
        $(this).slideToggle();
        var isShow = $(this).text() == 'Show';
        $(this).text(isShow ? 'Hide' : 'Show').css({backgroundPosition:'0 '+ (isShow?-18:0) +'px'});
    });    
});

Answer №5

Have a look at this demo: http://jsfiddle.net/yeyene/FPGH4/

To target multiple divs, add the target attribute.

HTML

<a class="show_hide" target="slidingDiv1">Show</a>
<div id="slidingDiv1" class="slidingDiv">
    Check out 1
</div>
<a class="show_hide" target="slidingDiv2">Show</a>
<div id="slidingDiv2" class="slidingDiv">
    Check out 2
</div>
<a class="show_hide" target="slidingDiv3">Show</a>
<div id="slidingDiv3" class="slidingDiv">
    Check out 3
</div>

JQUERY

$(document).ready(function(){ 
    $('.show_hide').on('click',function(){
        $('.show_hide').text(isShow ? 'Hide' : 'Show').css({backgroundPosition:'0 '+ (isShow?-18:0) +'px'});
        $(".slidingDiv").slideUp(100);
        $('#'+$(this).attr('target')).slideDown(300);
        var isShow = $(this).text() == 'Show';
        $(this).text(isShow ? 'Hide' : 'Show').css({backgroundPosition:'0 '+ (isShow?-18:10) +'px'});
    });
});

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

Is there a more efficient method than creating a separate variable for the navbar on each individual page where it is being utilized?

Apologies for the unclear title, I struggled to find the right wording and decided it would be easier to illustrate with code. Let's assume I have the following routes: router.get('/chest', (req, res)=>res.render('muscles/chest/chest ...

Whenever I use jQuery to dynamically add a new form input, the Select2 input fails to function properly

For my form, I'm attempting to dynamically add a new form-row each time the user clicks the add button. <div class="form-row mb-2"> <div class="form-group col-md-3 my-2"> <label>File</label> ...

Is it a Mozilla Firefox glitch or something else?

After writing the code, I noticed a bug in Firefox and a small bug in Chrome. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> ...

How to Make a Div Tag Fade Effect with JavaScript in an External File

*** New Team Member Notice *** I'm currently working on an assignment and trying to implement a simple fade effect on a box. While it seems like this should be straightforward, I'm encountering some obstacles. Currently, the button causes the bo ...

Navigate to the appropriate Angular route using HTML5 mode in Rails

After removing the '#' symbol in angular by using html5Mode, everything seemed to work fine. However, upon refreshing the page, it started looking for the template in Rails instead of Angular, resulting in a "template not found" error. Angular R ...

The array is devoid of any elements, despite having been efficiently mapped

I'm facing some challenges with the _.map function from underscore.js library (http://underscorejs.org). getCalories: function() { var encode = "1%20"; var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#"; _.m ...

Captivating Images accompanied by Descriptive Captions

I was wondering if there is a straightforward method using only CSS and HTML to address this particular issue. I am in the process of creating a marquee that displays images within a fixed-width div. The number of images exceeds the capacity of the div, ...

Use Jquery to iterate over the AJAX JSON response and add it to a collection of element identifiers

I have come across some similar inquiries, but none quite fit my needs. Currently, I am utilizing AJAX to obtain real-time updates on property availability. I have successfully received the response and can view it in the console log. However, I am unsure ...

What is the interaction between Vue's v-model and the update:modelValue directive, and how can we customize the default behavior to prevent it from

Could someone provide an explanation of the usage of v-model with :modelValue and update:modelValue? What happens when both are used together? In the code snippet below, a component is shown: <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3. ...

storing information in HTML using Django

Recently, I have been learning about Django Rest and I am now trying to display some JSON data in HTML. The JSON data I have is: {'Resul': {'Period Start': '2017-01-01', 'Period End': '2017-12-12'}} When ...

Exclude basic authentication for a specific route

Using node, express and connect for a simple app with basic HTTP auth implemented. The code snippet below shows part of the implementation: var express = require('express'), connect = require('connect'); app.configure = function(){ ...

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 ...

What is preventing the return type of document.createElement from being designated to a specific generic that is limited to HTMLElement?

Currently, I am in the process of developing a function called clone(el). This function needs to accept an HTMLElement or any subtype of it and return the same type that is provided. Can someone assist me in correctly structuring the generic signature for ...

Avoiding errors on the client side due to undefined levels in a specific response JSON can be achieved using the RESTful API

Below is a straightforward JSON response example: { "blog": { "title": "Blog", "paragraphs": [{ "title": "paragraph1", "content": "content1" }, { "title": "paragraph2", "content": "content2" }, { ...

Reset checkboxes in Material UI data grid

Currently, I am immersed in a React Js project that involves various tabs, each containing a unique data grid table with rows featuring checkboxes. Issue: Whenever I select a row from Table 1 and navigate to Tab 2 before returning to Tab 1, the checkboxes ...

strange occurrences of bootstrap.min.css.map popping up

While working on my e-commerce website using Node, Express, Mongoose, and Bootstrap, I encountered an unexpected issue related to "bootstrap.min.css.map". The error 'Cast to ObjectId failed for value "bootstrap.min.css.map" at path "_id" for model " ...

When scrolling, dynamically change the background color by adding a class

I am looking to achieve a scroll effect where the color of the menu buttons changes. Perhaps by adding a class when scrolling and hitting the element? Each menu button and corresponding div has a unique ID. Can anyone suggest what JavaScript code I should ...

Strategies for deactivating the next button when the input field is blank

I have been working on creating a multiple login form and everything was going well, but I am stuck on how to disable the next button if the email input is empty. The input has a class of "email" and the button has a class of "btn-next." Any assistance w ...

Creating a dynamic 3D pie chart with Highcharts and JSON data

I am attempting to create a 3D pie chart using HighChart with JSON data. Despite enabling the 3D option, it only displays in 2D. Here is an example of the 3D pie chart I am trying to achieve: https://www.highcharts.com/demo/3d-pie Could someone please he ...

It's time to wrap up the session with some old "cookies" and a closing function

Would like the message to only display once after clicking the "Cookies" button. Once the user accepts cookies, they should be stored on their device for a set period of time. Your assistance is greatly appreciated. :) Below is the html and js code: $(do ...