SlideToggle in jQuery does not work as it should!

0

I'm studying jQuery and I'm using slideToggle and as the documentation says, it should slide to its current opposite position.

I do not quite understand this but it just slides down.

$(document).ready(function(){

    $('li')
    .hide();

});

$('#btn-menu').click(function(){

    $('li')
    .toggle()
    .slideToggle();

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="btn-menu">MENU</button>
<ul id="menu">
  <li>Menu1</li>
  <li>Menu2</li>
  <li>Menu3</li>
  <li>Menu4</li>
</ul>
    
asked by anonymous 30.10.2018 / 02:53

2 answers

4

You are using two methods to hide and display the elements.

  • You hide the li elements:

    $('li').hide();
    
  • Then you use the toggle() method that will display the elements again, and then use the slideToggle() that will hide the elements.

    $('li').toggle().slideToggle();
    

The method toggle() will show or hide elements immediately when it is invoked:

$(document).ready(function(){
  $('li').hide();
  $('#btn-menu').click(function(){
    $('li').toggle();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="btn-menu">MENU</button>
<ul id="menu">
  <li>Menu1</li>
  <li>Menu2</li>
  <li>Menu3</li>
  <li>Menu4</li>
</ul>

The slideToggle() method will show or hide elements using an animation:

$(document).ready(function(){
  $('li').hide();
  $('#btn-menu').click(function(){
    $('li').slideToggle();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="btn-menu">MENU</button>
<ul id="menu">
  <li>Menu1</li>
  <li>Menu2</li>
  <li>Menu3</li>
  <li>Menu4</li>
</ul>
    
30.10.2018 / 03:30
1

The semantics is wrong, and what you want to display also, instead of displaying the li, you have to display the ul, and also do not need to dat toogle, and slidToogle slidToogle is the same function as toogle , but with sliding effect, leave your UL with display none straight in the css, so you do not need to start the document with a hide () your code should look like this:

$(document).ready(function(){
  $('#btn-menu').click(function(){
    $('#menu').slideToggle();
   });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="btn-menu">MENU</button>
<ul id="menu" style="display:none">
  <li>Menu1</li>
  <li>Menu2</li>
  <li>Menu3</li>
  <li>Menu4</li>
</ul>
    
30.10.2018 / 12:38