mpora
mpora

Reputation: 1479

slideToggle not a function

I am trying to toggle a ul but getting an error saying that "slideToggle is not a function". The menu is used to toggle through a list.

    $(function() {
        $("li ul").hide();

        var currentChildLevel;
        var previousLevel;
        var isAChild; //means it belongs to parent li

        $("li ul").hide();
        $("li > a + ul").prev("a").after('<span class="children"> > </span>');

        $("li a").click(function () {
            console.log($(this).text());
        });


        $("span.children").click(function() {
            $(this).find('ul').first().slideToggle();
        });


    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
</head>
<body>

<ul>
    <li><a href="#">Coffee</a></li>
    <li><a href="#">Tea</a>
        <ul>
            <li><a href="#">Black tea</a></li>
            <li><a href="#">Green tea</a>
                <ul class="test">
                    <li><a href="#">Black b</a></li>
                    <li><a href="#">Black c</a></li>
                </ul>
            </li>
        </ul>
    </li>
    <li><a href="#">Milk</a></li>
</ul>

</body>
</html>

Basically when users click the >, the submenu should be shown.

Upvotes: 0

Views: 838

Answers (1)

fubar
fubar

Reputation: 17398

I cannot reproduce the slideToggle is not a function error you mention.

However your code will not work, because this line is incorrect:

$(this).find('ul').first().slideToggle();

The ul element is a sibling, not a child of the span.children element. Changing it to the following resolves the issue:

$(this).siblings('ul').first().slideToggle();

$(function() {
    $("li ul").hide();

    var currentChildLevel;
    var previousLevel;
    var isAChild; //means it belongs to parent li

    $("li ul").hide();
    $("li > a + ul").prev("a").after('<span class="children"> &gt; </span>');

    $("li a").on('click', function () {
      console.log($(this).text());
    });


    $("span.children").on('click', function() {
      $(this).siblings('ul').first().slideToggle();
    });
});
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
  <head>
      <meta charset="utf-8" />
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  </head>
  <body>
    <ul>
        <li><a href="#">Coffee</a></li>
        <li><a href="#">Tea</a>
            <ul>
                <li><a href="#">Black tea</a></li>
                <li><a href="#">Green tea</a>
                    <ul class="test">
                        <li><a href="#">Black b</a></li>
                        <li><a href="#">Black c</a></li>
                    </ul>
                </li>
            </ul>
        </li>
        <li><a href="#">Milk</a></li>
    </ul>
  </body>
</html>

Upvotes: 1

Related Questions