Toggling display of divs with jQuery using plus and minus icons

Is it possible to use two different icons as a sprite image for when the show and hide functions are active on a div element?

For instance, having a + icon displayed when showing the div, and then switching to a - icon when hiding it.

The current code I have is: http://jsfiddle.net/BLkpG/

$(document).ready(function(){
   $(".slidingDiv").hide();
   $(".show_hide").show();

    $('.show_hide').click(function(){
    $(".slidingDiv").slideToggle();
  });
});

I am looking to update the images dynamically to display a + or - icon based on the toggle action.

Any guidance on how to achieve this would be greatly appreciated. Thank you!

Answer №1

Here is a suggestion for you to try out:

Using jQuery:

$('#toggle_icon').toggle(function() {

    $('#toggle_icon').text('-');
    $('#toggle_text').slideToggle();

}, function() {

    $('#toggle_icon').text('+');
    $('#toggle_text').slideToggle();

});

Incorporating HTML:

<a href="#" id="toggle_icon">+</a>

<div id="toggle_text" style="display: none">
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
</div>

Check out the DEMO for a live example!

Answer №2

In my opinion, the most stylish method is as follows:

<div class="toggler"></div>
<div class="display">...</div>

then add some CSS:

.toggler{
 display:inline-block;
height:48px;
width:48px;
background:url("http://icons.iconarchive.com/icons/pixelmixer/basic/48/plus-icon.png");
}
.toggler.active{
  background:url("http://cdn2.iconfinder.com/data/icons/onebit/PNG/onebit_32.png");
}

and include some JavaScript:

$(document).ready(function(){
  var $content = $(".display").hide();
  $(".toggler").on("click", function(e){
    $(this).toggleClass("active");
    $content.slideToggle();
  });
});

CODE DEMO

Answer №3

Switch between displaying the text Show and Hide, while adjusting the position of your backgroundPosition on the Y axis

VIEW LIVE DEMO

$(function(){ // When DOM is ready

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

    $('.show_hide').click(function( e ){
        var SH = this.SH^=1; // Toggle switch
        $(this).text(SH?'Hide':'Show')
               .css({backgroundPosition:'0 '+ (SH?-18:0) +'px'})
               .next(".slidingDiv").slideToggle();
    });

});

CSS:

.show_hide{
  background:url(plusminus.png) no-repeat;
  padding-left:20px;  
}

Answer №4

Enve's answer has been quickly edited here. While roXor's solution is appreciated, background images are deemed unnecessary. Additionally, it seems that everyone forgot to include a preventDefault as well.

$(document).ready(function() {
  $(".slidingDiv").hide();

  $('.show_hide').click(function(e) {
    $(".slidingDiv").slideToggle("fast");
    var val = $(this).text() == "-" ? "+" : "-";
    $(this).hide().text(val).fadeIn("fast");
    e.preventDefault();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="show_hide">+</a>

<div class="slidingDiv">
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta.
    Mauris massa. Vestibulum lacinia arcu eget nulla. </p>

  <p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis.
    Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. </p>

</div>

Answer №5

this method is effective:

http://jsfiddle.net/UhEut/

Styling with CSS:

.show_hide {
    display:none;
}
.plus:after {
    content:" +";
}
.minus:after {
    content:" -";
}

Using jQuery:

$(document).ready(function(){
  $(".slidingDiv").hide();
  $(".show_hide").addClass("plus").show();
  $('.show_hide').toggle(
      function(){
          $(".slidingDiv").slideDown();
          $(this).addClass("minus");
          $(this).removeClass("plus");
      },
      function(){
          $(".slidingDiv").slideUp();
          $(this).addClass("plus");
          $(this).removeClass("minus");
      }
  );
});

Incorporating in HTML:

<a href="#" class="show_hide">Show/hide</a>

<div class="slidingDiv" style="display: block;">
Check out the updated jQuery plugin for doing this: <a href="http://papermashup.com/jquery-show-hide-plugin/" class="show_hide" target="_blank" style="display: inline;">jQuery Show / Hide Plugin</a>
</div>

In the CSS, instead of using content:" +";, consider utilizing a background-image (with

background-position:right center;
and background-repeat:no-repeat) and possibly setting the .show_hide to be displayed as a block with a width to prevent overlaying of the link text).

Answer №6

Instead of using a simple plus (+) and minus (-) sign, you can opt for an arrow to show and hide elements. This method involves utilizing jQuery to toggle classes on the element and CSS to style the arrow accordingly.

$(".toggleHide").click(function() {
  $(".elementToHide").slideToggle("fast");
  $(this).find("i").toggleClass("down up");
});
i {
  border: solid black;
  border-width: 0 5px 5px 0;
  display: inline-block;
  padding: 5px;
  -webkit-transition-duration: 1s;
  transition-duration: 1s;
}

.up {
  transform: rotate(-135deg);
  -webkit-transform: rotate(-135deg);
}

.down {
  transform: rotate(45deg);
  -webkit-transform: rotate(45deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h3 class="toggleHide"><i class="down"></i></h3>
<aside class="elementToHide">
  Content to hide
</aside>

Answer №7

HTML:

<div class="Settings" id="GTSettings">
  <h3 class="SettingsTitle"><a class="toggle" ><img src="${appThemePath}/images/toggle-collapse-light.gif" alt="" /></a>General Theme Settings</h3>
  <div class="options">
    <table>
      <tr>
        <td>
          <h4>Back-Ground Color</h4>
        </td>
        <td>
          <input type="text" id="body-backGroundColor" class="themeselector" readonly="readonly">
        </td>
      </tr>
      <tr>
        <td>
          <h4>Text Color</h4>
        </td>
        <td>
          <input type="text" id="body-fontColor" class="themeselector" readonly="readonly">
        </td>
      </tr>
    </table>
  </div>
</div>

<div class="Settings" id="GTSettings">
  <h3 class="SettingsTitle"><a class="toggle" ><img src="${appThemePath}/images/toggle-collapse-light.gif" alt="" /></a>Content Theme Settings</h3>
  <div class="options">
    <table>
      <tr>
        <td>
          <h4>Back-Ground Color</h4>
        </td>
        <td>
          <input type="text" id="body-backGroundColor" class="themeselector" readonly="readonly">
        </td>
      </tr>
      <tr>
        <td>
          <h4>Text Color</h4>
        </td>
        <td>
          <input type="text" id="body-fontColor" class="themeselector" readonly="readonly">
        </td>
      </tr>
    </table>
  </div>
</div>

JavaScript:

$(document).ready(function() {

  $(".options").hide();
  $(".SettingsTitle").click(function(e) {
    var appThemePath = $("#appThemePath").text();

    var closeMenuImg = appThemePath + '/images/toggle-collapse-light.gif';
    var openMenuImg = appThemePath + '/images/toggle-collapse-dark.gif';

    var elem = $(this).next('.options');
    $('.options').not(elem).hide('fast');
    $('.SettingsTitle').not($(this)).parent().children("h3").children("a.toggle").children("img").attr('src', closeMenuImg);
    elem.toggle('fast');
    var targetImg = $(this).parent().children("h3").children("a.toggle").children("img").attr('src') === closeMenuImg ? openMenuImg : closeMenuImg;
    $(this).parent().children("h3").children("a.toggle").children("img").attr('src', targetImg);
  });

});

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

Exporting an HTML table to Excel with JavaScript runs into issues when it encounters the '#' character

Looking for a JavaScript solution to export HTML tables to Excel. I attempted a script that exports tables, but it stops when encountering special characters like '#'. Can someone assist me with this issue? Thank you in advance. <script src= ...

Interacting with a card in vuejs won't trigger any action

Is there a way to make an overlay disappear when clicking anywhere on the screen except for a specific card positioned on top of it? The current setup makes the overlay disappear even when the card is clicked. How can this behavior be corrected? <div ...

Is it possible to target an iframe and display text simultaneously?

Trying to create a unique menu that interacts with an iframe and displays text in a separate div upon clicking. Example: • Menu item 1 clicked. • "https://wikipedia.org" loads in the iframe. • Address of the wikipedia page displayed in a diffe ...

Adjusting the overflow of a parent div based on the position of the div within it by scrolling

I'm trying to create a page with 3 different sections: <div class="container" id="main-container"> <div class="section" id="profile"> Hello World </div> <div class="section" id="projects"> Hello World 2 ...

When attempting to upload a file using Form, it only allows for a single upload of that file and will not work when attempting to upload the same file again

After selecting a file from the file chooser and uploading it, I encounter an issue when attempting to submit the form with the same file again. The submission doesn't seem to trigger any action. If I select a file, upload it, then choose the same fi ...

Is there a way to assign a value of 1 to the input-group spinner?

At first, I thought this problem would be easy to solve, but now I'm finding myself stuck. My goal is to have the input-group spinner display the value 1 when a user opens the application. <input id="option1" type="number" min="1" value ="1" ...

Tips for adjusting font size automatically to fit within its parent container every time

On my blog, the post titles are displayed in a div with a video playing in the background. The length of the title varies, ranging from 2 words to over 20 words. When the title is too long, it may overflow from its parent container where the video is playi ...

Update the "Select" element to be a "DIV

Recently, I came across a code snippet that converts a select element into a DIV. You can check out the code snippet here: http://jsfiddle.net/mBUgc/21/ var selectName = jQuery('select').attr('name'); // add a hidden element with the ...

jQuery fails to post serialized data to the action method

I'm facing an issue with submitting a form using jQuery and Ajax. My Ajax function looks like this: $('#submitForm').click(function (e) { e.preventDefault(); $.ajax({ url: '/Letter/Create', ...

A guide on integrating mat-select into Angular input fields

I've been trying to implement a mat-select dropdown on my input field, but for some reason, when I click on the arrow, nothing happens and the list doesn't show up. Usually, with autocomplete, when a user starts typing, all the options are displ ...

Trigger the click event on a specific class selector to extract the corresponding ID

I have an HTML Table with each row: <table> <tr><td><a href='#' id='1' class='delete'>delete</a></td></tr> <tr><td><a href='#' id='2' class='de ...

Adjust the size of a div while maintaining its aspect ratio based on the width and height of its parent element using CSS

After exploring various methods to create div aspect ratios using CSS, I had success with a demo. However, I encountered an issue with setting the height of my container when the width-to-height ratio is larger (#1 scenario). I was able to achieve the #2 ...

Sliding elements horizontally with jQuery from right to left

I recently purchased a WordPress theme and I'm looking to customize the JavaScript behavior when the page loads. Currently, my titles animate from top to bottom but I want to change this behavior dynamically. You can view it in action here: I have ...

Seamlessly adaptive HTML5 video playback

Has anyone figured out how to make an HTML5 video in an absolutely positioned <video> element resize to fit the window width and height without ever getting cropped? Many solutions I've come across rely on using the <iframe> tag, which is ...

Using HTML and JavaScript to add variables into the URL within the window.location

I have been struggling to incorporate longitude and latitude into the URL. Despite researching various topics online, I have not found a solution that works for me. Below is the HTML code that showcases the issue. When you click the "Show Position" button ...

CodeMirror version 5.62.3 is experiencing some challenges with the scrollbar functionality, editor size, and line wrapping

During my HTML/CSS/JS coding session, I encountered a challenge with CodeMirror version 5.62.3. Specifically, I was striving to make the scrollbar visible in the code editor, using C# as the language mode. However, despite setting the editor's height ...

Modify text input when a different option is selected (with both options originally coming from a database)

A dropdown menu is filled with options from a database, and the chosen option is compared to a variable $comp_cntry currently on the page: <select name="country"> <option value="--" disabled>Please Select...</option> <option v ...

What is the best way to apply a background-image to a DIV while also implementing a double line border to prevent the image from showing through the border?

Within my DIV, I have applied a background-image and added a double border to the DIV. The image is currently visible in between the lines. Is there a method to resolve this issue and prevent the image from displaying in this manner? ...

Achieve a distinctive effect with jQuery: exhibiting a sole div upon

Hello everyone, I'm encountering an issue with this small script. Whenever I hover over the "item" div, both divs display the "dark-overlay". However, my intention is for only the dark-overlay inside the hovered div to appear. Is there a way to achiev ...

A tutorial on how to customize the hover effect for TableHead Column Identifiers in MaterialUI by adjusting

I'm struggling to customize the appearance of child th elements using the TableHead component from MaterialUI. While I've been successful in modifying various properties, I'm facing difficulty in changing the hover color. Below is the snipp ...