Search code examples
javascriptslidetoggle

slidetoggle empty div should not work


$('.cat').click(function(){
    if ($(this).next().text() == '') {
        return false;
    }

    $(this).next().slideToggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='themea cat'>lorem ipsum</div>
<div class='titlewrap'>
    <ul></ul>
</div>
<div class='themea cat'>lorem ipsum</div>

next to cat is titlewrap and has no text. Still, click on cat is trying to slideToggle it.


Solution

  • You need to trim the string to avoid whitespace.

    $('.cat').click(function() {
      if ($(this).next().text().trim() == '') {
        return false;
      }
      $(this).next().slideToggle();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class='themea cat'>lorem ipsum</div>
    <div class='titlewrap'>
      <ul>
      </ul>
    </div>
    
    <div class='themea cat'>lorem ipsum</div>