Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 667
hhffh fhfg Avatar asked Aug 30 '17 07:08

hhffh fhfg


2 Answers

make sure, NOT to use the slim version of jquery, which excludes the effects like the animation.

like image 179
simUser Avatar answered Oct 21 '22 05:10

simUser


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();
  });
});
like image 42
Rory McCrossan Avatar answered Oct 21 '22 04:10

Rory McCrossan