What to do for this code to work on your phone

2

I've got this code ready to mount a fake off-canvas menu, it's working perfectly, but when I go to the mobile the menu does not appear, what do I need to do?

$(".toggle-canvas").click(function () {
$("#menu-canvas").toggleClass('menu-canvas-active');
    removeClass = false;
});

$("#menu-canvas").click(function() {
    removeClass = false;
});
$("html").click(function () {
    if (removeClass) {
        $("#menu-canvas").removeClass('menu-canvas-active');
    }
    removeClass = true;
})

Another question, does addClass work on mobile?

    
asked by anonymous 20.12.2014 / 20:59

1 answer

1

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;
    });
}());
    
24.12.2014 / 16:42