Keep variable value between layers of a function

1

I wanted to make a website where when I click on the image it doubles in size and width, but can only do it once, and if you do more, a warning will appear to prevent it. Likewise, if it is in the default size, you can not decrease it, and a warning will appear, but if you increase it and try to decrease it, it will be possible.

I stopped in the code here:

function passar(img){
        var d = 0;
        if (d == 0){
        var x = confirm("tem certeza que deseja aumentar a imagem?");
        if(x == true && d ==0){
        d=d+1;
        img.height=img.height*2;
        img.width=img.width*2;
        }
        else if (x== true && d==1)
        window.alert("Não é possivel aumentar mais");
        else{
        var y = confirm("tem certeza que deseja diminuir a imagem?");
        if ( y==true && d==1){
        d=d-1;
        img.height=img.height/2;
        img.width=img.width/2;
        }
        else if(y == true && d==0)
        window.alert("Não é possivel");
        }}}

My biggest problem is that when a if-else closes the key, d does not have the new value that I gave d=d+1 or d=d-1 , I tried other ways but I do not find a solution.

    
asked by anonymous 12.03.2016 / 20:20

1 answer

2

Organizing the code always helps, it's very easy to fool around where every if closes, it's a nightmare to maintain code so I lost several minutes to understand what you're really doing and I have my doubts if I got it right. The names of the variables should be more meaningful. I did not check if the logic is correct.

In this case it is necessary to make the variable be considered an instance of the function for its value maintained between runs. Also it should only initialize if it was not initialized, so we use a relational operator

function passar(img) {
    passar.contador = passar.contador || 0;
    if (passar.contador == 0) {
        var confirma = confirm("Tem certeza que deseja aumentar a imagem?");
        if (confirma && passar.contador == 0) {
            passar.contador++;
            img.height *= 2;
            img.width *= 2;
       } else if (confirma && passar.contador == 1) {
            window.alert("Não é possível aumentar mais");
        }
    } else {
        var confirma = confirm("Tem certeza que deseja diminuir a imagem?");
        if (confirma && passar.contador == 1) {
            passar.contador--;
            img.height /= 2;
            img.width /= 2;
        } else if (confirma && passar.contador == 0) {
            window.alert("Não é possível diminuir mais");
        }
    }
}
var img = {height : 10, width : 10};
passar(img);
passar(img);

I left as a counter because I may in the future want to allow new scales, in the current form, nor need to be a numeric counter, since there are only two possible states.

Of course there are other solutions.

    
12.03.2016 / 21:08