Search code examples
jquerytoggleslidetoggle

jQuery slideToggle without the elements animating


I want to use the jQuery method .slideToggle on a div without its content animating, but I can't seem to get that working. All the elements inside that div move when I use .slideToggle on it, including the arrow (which I don't want moving). Please check out my fiddle https://jsfiddle.net/ch4jmqz8/

This is the JS code I am using:

$('#tgl').on('click', function () {
    $('.toggled_div').slideToggle();
});

CSS:

.toggled_div {
    background: #3597FF;
    padding: 15px;
    width: 300px;
    margin-top: 20px;
}
.toggled_div:before {
        content: '';
    position: absolute;
    left: 20px;
    margin-top: -34px;
    border: 10px solid transparent;
    border-bottom-color: #3597FF;
}
.toggled_div div {
  background: #ddd;
  padding: 10px;
  margin: 10px;
} 

Solution

  • Ok, here's a pure CSS solution where instead of a div#tgl we can make use of the pseudo selector :checked of a checkbox, also we need to hide the checkbox with display:none and relying on on clicking its label for="" to toggle the transition.

    As the hidden checkbox gets checked status by its label , this #toggle:checked ~ .slider condition will be applied and we change the max-height property to 200px instead of its original value 0, and this property is the one which will be affected by this transition: all 1s;

    As the transition line animates the max-height property, the rule of this overflow: hidden in the .slider will reveal content as the transitioned max-height value changes, same above is said about when the checkbocx status changes to unchecked.

    JS Fiddle

    .toggled_div {
      background: #3597FF;
      width: 300px;
      margin-top: 20px;
      padding: 15px;
    }
    .toggled_div:before {
      content: '';
      position: absolute;
      left: 20px;
      top: 0;
      border: 10px solid transparent;
      border-bottom-color: #3597FF;
    }
    .slider {
      width: 300px;
      max-height: 0;
      overflow: hidden;
      position: relative;
      -webkit-transition: all 1s;
      transition: all 1s;
    }
    #toggle {
      display: none;
    }
    label[for="toggle"] {
      cursor: pointer;
    }
    #toggle:checked ~ .slider {
      max-height: 200px;
    }
    <input id="toggle" type="checkbox">
    <label for="toggle">toggle</label>
    <div class="slider">
      <div class="toggled_div">
        some text here
        <br>some text here
        <br>some text here
        <br>some text here
        <br>some text here
        <br>
      </div>
    </div>