Slidetoggle in jQuery does not work as it should!

Asked

Viewed 97 times

0

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

I don’t quite understand it 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>
<button id="btn-menu">MENU</button>
<ul id="menu">
  <li>Menu1</li>
  <li>Menu2</li>
  <li>Menu3</li>
  <li>Menu4</li>
</ul>

  • Why are you using toggle() before, just do $('li').slideToggle();

2 answers

4

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

  • You hide the elements li:

    $('li').hide();
    
  • Then use the method toggle() which will display the elements again, and then uses the method slideToggle() which will conceal 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>
<button id="btn-menu">MENU</button>
<ul id="menu">
  <li>Menu1</li>
  <li>Menu2</li>
  <li>Menu3</li>
  <li>Menu4</li>
</ul>

Already the method slideToggle() will show or hide the 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>
<button id="btn-menu">MENU</button>
<ul id="menu">
  <li>Menu1</li>
  <li>Menu2</li>
  <li>Menu3</li>
  <li>Menu4</li>
</ul>

1

The semantics is wrong, and what you want to display too, instead of you displaying the li, has to display the ul, and also does not need dat toogle, and slidToogle the slidToogle is the same function as the toogle, only with sliding effect, leave your UL with None display right in css, so you don’t need to start the document with an 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>

<button id="btn-menu">MENU</button>
<ul id="menu" style="display:none">
  <li>Menu1</li>
  <li>Menu2</li>
  <li>Menu3</li>
  <li>Menu4</li>
</ul>

  • Dude, I checked the question issues and the AP was using jQuery correctly. Didn’t you get confused because it’s a Stackoverflow Snippet?

  • Boy, could I, I’ll edit, I’m new here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.