Toggle status (True/False) by clicking a button - Javascript

Asked

Viewed 824 times

2

Good night!

I am testing and learning JS, and there was a doubt that so far I could not solve. I have a simple HTML page, where the idea is that every time I click a button, I want it to have an effect, and if I click again, it removes the effect (and so on, always alternating the state to click).

I can make it stick with the effect by clicking the button, but I can’t make it remove the effect when I click again.

I’ve tested some forms and logics, but I can’t do it. The idea I had was to check the "status" of the button, if it is TRUE, it changes the color, otherwise it will take the color, but my validation always falls to TRUE.

I believe the problem is in the function setState(), because it always takes the variable state as null, making it always send TRUE, but I don’t know how I could "record" the last information of the variable, I tried to put it to receive a function that would save the state, but without success. I would like ideas to solve this logic. (below is the code compiling)

var button_MudaCor = document.querySelector("#mudarCor");

button_MudaCor.onclick = function mudaEstado() {
	if (pegaEstado() == true) {
		mudaCor(true);
	} else {
		mudaCor(false);
	}
};

function pegaEstado() {
	var estado = guardaEstado();

	if (estado == null || estado == true) {
		guardaEstado(true);
		estado = true;
	} else {
		guardaEstado(false);
		estado = false;
	}
	return estado;
};

function guardaEstado(teste) {
	this.teste = teste;
};

function mudaCor(state) {
	if (state == true) {
		button_MudaCor.className = "changeColor";
	} else {
		button_MudaCor.className = "";
	}
};
.changeColor {
	border-style: outset;
	border-top-style: none;
	border-left-style: none;
	box-shadow: 3px -3px 8px 1px  grey ;
}
<!DOCTYPE html>
<html>
<head>
	<title>Login</title>
	<meta charset="utf-8">
	<link rel="stylesheet" type="text/css" href="style/style_index.css">
	<link href="https://fonts.googleapis.com/css?family=Inter|Roboto+Condensed&display=swap" rel="stylesheet">
</head>
<body>

	<header></header>

	<main>
		<section class="login">
			<h2>Faça o login ou cadastra-se</h2>
			<div>
				<input type="text" id="usuario" autocomplete="name" placeholder="Usuário ou e-mail">
				<input type="password" autocomplete="current-password" id="senha" placeholder="Senha">
				<button class="botao" id="logar">Login</button>
				<button class="botao" target="_self" id="cadastrar">Cadastrar</button>
				<button class="botao" id="mudarCor">Mudar cores</button>
			</div>
		</section>
	</main>
	<footer></footer>
	<script type="text/javascript" src="../Model/model.js"></script>
	<script type="text/javascript" src="../Controller/controller.js" aynsc></script>
</body>
</html>
							

  • 1

    Dude, there’s a lot of unnecessary stuff in your code for the purpose of just changing one color. What do you really want to learn from this code?

  • @Franckcosta, the idea was actually to create a more "pure" logic for the goal, without using JS/ES6’s own resources, but using only conditional and repetitive.

  • I understand, I gave an answer by adapting your code, but what @fwerther did is the simplest and most correct way to do it.

2 answers

4

I found your code a bit messy, but if the goal was just to change the colors, see if this example answers your problem:

var button_MudaCor = document.querySelector("#mudarCor");

button_MudaCor.addEventListener('click', function (event) {

  if (button_MudaCor.classList.contains('changeColor')) {
    button_MudaCor.classList.remove('changeColor');
  } else {
    button_MudaCor.classList.add('changeColor');
  }

}, false);

You can see the example running on https://jsfiddle.net/knvg6h2o/

  • 1

    It solves the problem (it was exactly that rsrsrs). Is that the idea itself was to do the process without using too much the resources of JS/ES6, just to train logic (but really, its mode is the most correct).

4


Dude, as @fwerther mentioned, something for just the class change and what he did caters to your needs. However, I adapted your code to make more sense, if you want to have the dynamics of saving the state for some kind of processing afterwards, you have to change it as soon as you receive the information, for example if you receive it as true then you need to guard it as false, for later managed to make the changes. In what you did he always keeps the state as true, so there will never be change.

var stateClass = true;
var button_MudaCor = document.querySelector("#mudarCor");

button_MudaCor.onclick = function mudaEstado() {
    if (pegaEstado() == true) {
        mudaCor(true);
        guardaEstado(false);
    } else {
        mudaCor(false);
        guardaEstado(true);
    }
};

function pegaEstado() {
    return stateClass;
};

function guardaEstado(teste) {
    stateClass = teste;
};

function mudaCor(state) {
    if (state == true) {
        button_MudaCor.className.add('changeColor');
    } else {
        button_MudaCor.classList.remove('changeColor');
    }
};
  • Show, I hadn’t thought of it. It would be like using a GET and SET?

  • Exactly, GET to take the value and SET to return this value, in logic these functions serve only for this, without decision making.

  • Perfect, thanks for the help, gave a good enlightened.

  • 2

    If you’re interested in keeping the value and not just changing the color it’s worth staying connected in the ES6 syntax of getters and setters. You should define the methods in a standardized way, get property() and set property(value). Then after setting thus you can use direct object.property or object.property = value. More information on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set and https://coryrylan.com/blog/javascriptes6-class-syntax

Browser other questions tagged

You are not signed in. Login or sign up in order to post.