here is the code, I have a menu global variable inside the function. I want to use it outside it, but then I get an “undefined reference error…·
This is the only javascript code I have, so there’s no interference with another variables or functions.
Thanks in advance.
$(function() {
menu = $('nav#menu').mmenu(
{
navbars: [
{
position: "top",
height : 1,
content : [
'<a href="#/" class="fa fa-phone"></a>',
'<img src="imagenes/wheel32.png" /><p class="navbartxt">bicimap.uy</p>',
]
},
{
position: "bottom",
content: [
'<a class="fa fa-envelope"></a>',
'<a class="fa fa-twitter"></a>',
'<a class="fa fa-facebook"></a>'
]
}
],
extensions: ["multiline"],
onClick: {
close: false
},
navbar:{
title: "Inicio"
},
offCanvas: {
zposition : "next"
}
});
});
I need to put this inside the function to get it working
var API = $("#menu").data( "mmenu" );
menu.on( 'click', 'a[class^="fa fa-twitter"]', function() {
$('#twitter').show();
var API = $("#menu").data( "mmenu" );
API.close();
return false;
});
3
Answers
This is the solution I found, maybe it's not the best because it could bring problems. For some reason the ready function doesn't work as is shown above, maybe some assets are being expected.
I’m lacking some context here (I’m assuming there’s more we don’t see?)
But you may be executing the latter snippet,
menu.on( 'click'…
before the code inside$(…)
has run (on dom ready); somenu
would be undefined.If you’re just getting started, it’s worth looking into your browser’s developer tools and learning about break points and logging.
You’ll need to make sure that you use
menu
only after it’s been set, likely by delaying all your invocation to be on ready.Execution Order
The
$
is called and the function is provided as the first and only argument. The function itself is not called.API
is defined by the result of$("#menu"
) This may or may not be found yet depending upon where in the html file you’ve added this script.The
data
method is invoked on the result of thatYou try to call
on
onmenu
, which is still undefinedsometime later, the function you passed to
$
is called, and menu ends up being defined, to late to be usefulIf your closure/anonymous function is happening asynchonously, its possible that the work has not been done by the time the rest of your code is computed. I would need more context to determine that.