First of all, its removeClass
variable is not defined, this can end up mixing with variables of a higher level or global, so always use var ...
Or, avoid creating the events in the "first level" of the javascript (would be the global level), something like:
<script>
var oi = 1;
</script>
Prefer something like:
<script>
(function () {
var oi = 1;
}());
</script>
So you can avoid mixing the variables
Following up with this something you could do would be to use the .on
event of Jquery instead of .click
(equivalent to .bind("click",
)
Events .on
checks for changes in DOM
, if a new object is added, it automatically applies the event. I say this because I believe that you are trying to add the .click
event when the object has not yet been rendered.
An example of .on
would be:
$(document).on("click", "SELETOR", function () { console.log("Test..."); });
In your case, your script might work like this:
(function () { //"Isola" as variáveis
var removeClass = false;//Define a variável
//Configura o click para o elemento .toggle-canvas, assim que este "existir"
$(document).on("click", ".toggle-canvas", function () {
$("#menu-canvas").toggleClass('menu-canvas-active');
removeClass = false;
});
//Configura o click para o elemento #menu-canvas, assim que este "existir"
$(document).on("click", "#menu-canvas", function() {
removeClass = false;
});
//Não é necessário .on aqui, pois o document é um dos primeiros elementos "dentro do javascript" a existirem
$(document).click(function () {
if (removeClass) {
$("#menu-canvas").removeClass("menu-canvas-active");
}
removeClass = true;
});
}());