Search code examples
jqueryjquery-uijquery-ui-accordiondestroy

jQuery UI accordion destroy not working


I've hit a problem deleting the accordion widget when the window is resized above a set point.

I'm using jQuery 1.8.3 and the jQuery UI 1.9.2.

This is my code:

/*
* Detect browser size and add accordian on page (at load) if necessary
*/
$(document).ready(function() {
    var window_width = $(window).width();  
    if (window_width <= 767){
        $("div.innernav ul.menu").accordion({ 
            header: '.separator',
            animated: 'slide',
            event: "click",
            heightStyle: "content",
            icons: { "header": false, "headerSelected": false } ,
            collapsible: true, 
            active: false,
        });
    }
});
/*
* Detect browser size on resize and add/remove accordian
*/
$(window).resize(function() {
    var wi = $(window).width();
    if (wi <= 767){
        $("div.innernav ul.menu").accordion({ 
            header: '.separator',
            animated: 'slide',
            event: "click",
            heightStyle: "content",
            icons: { "header": false, "headerSelected": false } ,
            collapsible: true, 
            active: false,
        });
    } else if (wi >= 768){
        $("div.innernav ul.menu").accordion("destroy");
    }
});

The code works and my accordion is only active when window width is smaller than 768px but I get an:

Error: cannot call methods on accordion prior to initialisation; attempted to call method 'destroy'

It seems this error makes other code I have on the page bork so I could do with removing this error. I'm a javascript/jQuery newbie so would really appreciate a helping hand.

Many thanks!


Solution

  • Try changing your ready function into a separate function.

    Within the else portion:

    $("div.innernav ul.menu").empty();
    

    Then just reifill the ul menu the same as the ready function.