Skip to content
Advertisement

Uncaught TypeError: .slideToggle is not a function

I have jquery in a different file located in the same map, I’m using this code below to activate the .slideToggle function. However it’s not working, why?

jQuery(document).ready(function ($) {

    // get li items
    var ul = document.getElementById("menu-footermenu");
    var items = ul.getElementsByTagName("li");

    // display 5 li items, hide others
    for (var i = 0; i < items.length; ++i) {
        if (i > 5) {
            items[i].style.display = "none"
        }
    }

    // when clicking on more catogories button, display all items
    $('#morecat').click(function () {
        for (var i = 0; i < items.length; ++i) {
            if (i > 5) {
                items[i].slideToggle();
                document.getElementById("morecat").style.display = "none";
            }
        }
    });
});

I’m getting the error:

Uncaught TypeError: .slideToggle is not a function

Advertisement

Answer

Firstly ensure you’re not using the ‘slim’ branch of jQuery as it does not include animation or AJAX functionality, amongst others. You will need to use the full version of jQuery in this instance.

In addition, items in your code will be a collection of Element objects, not jQuery objects, hence the slideToggle() function is not available on them.

To fix this you need to convert them:

$(items[i]).slideToggle();

Alternatively, you can convert all the logic to use jQuery, instead of the rather odd half/half solution you have now:

jQuery(function ($) {
  var $ul = $("#menu-footermenu");
  var $items = $("li");
  $items.filter(':gt(4)').hide();

  $('#morecat').click(function () {
    $items.filter(':gt(4)').slideToggle();
    $(this).hide();
  });
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement