user1406440 user1406440 - 1 month ago 10
CSS Question

JS plug-in breaks other scripts when not required on page

I'm using a plug-in for my responsive navigation (http://responsive-nav.com). The plug-in works great, the problem I'm having is there is not navigation on every page. When this is the case I've noticed other javascript doesn't load and I get an error in reference to "responsive-nav.js":


Uncaught Error: The nav element you are trying to select doesn't exist


Here's how I load the script in the main.js file.

$(function(){

var navigation = responsiveNav(".site-nav__list", {
customToggle: "#site-nav__toggle",
open: function(){
$("#site-nav__toggle").addClass('open');
},
close: function(){
$("#site-nav__toggle").removeClass('open');
}
});
});;


The file is called on each page (/js/responsive-nav.js) but removing it doesn't resolve the issue, commenting out the code I've typed above does - so I'm guessing it's something to do with that?

Hope someone can help, cheers!

Answer

After speaking with the author of the plug-in he advised I just wrap the script in an 'if statement'.

Here's what we ending up using:

$(function(){
    if ($(".site-nav__list").length) {
        var navigation = responsiveNav(".site-nav__list", {
            customToggle: "#site-nav__toggle",
            open: function(){
                $("#site-nav__toggle").addClass('open');
            },
            close: function(){
                $("#site-nav__toggle").removeClass('open');
            }
        });
    }
});

Simple. Works like a charm :)