¿Cómo va todo? Estoy haciendo un proyecto de JavaScript y debo dar la opción de seleccionar algunos botones y si un botón ya presionado se vuelve a presionar, el programa debe deseleccionarlo y volver al estado de ningún botón presionado. Busqué en algunos foros y documentación, logré hacer la parte de seleccionar una opción, pero no pude hacerlo, de modo que al hacer clic en el botón nuevamente, todos los botones están sin selección. ¿Alguien me puede ayudar? Muchas gracias
const circle = document.querySelectorAll('.circle'); for (let i = 0; i < circle.length; i++) { const el = circle[i]; el.onclick = () => { for (let j = 0; j < circle.length; j++) { const color = circle[j] === el ? 'hsl(25, 97%, 53%)' : '#262d37'; circle[j].style.backgroundColor = color; } } } const submit = document.querySelectorAll('.btn'); for (let i = 0; i < submit.length; i++) { const el = submit[i]; el.onclick = () => { for (let j = 0; j < submit.length; j++) { const color = submit[j] === el ? '#fff' : 'hsl(25, 97%, 53%)'; submit[j].style.backgroundColor = color; submit[j].style.color = 'hsl(25, 97%, 53%)'; } } } .circle { border-radius: 50%; width : 15px; height : 15px; padding : 10px; margin-left : 20px; display : inline-block; background : #262d37; color : #e7eaec; text-align : center; } .circle:hover { border-radius: 50%; width : 15px; height : 15px; padding : 10px; margin-left : 20px; display : inline-block; transition : 0.5s; opacity : 0.7; color : #e7eaec; text-align : center; } .btn { background-color: hsl(25, 97%, 53%); color : #e7eaec; margin-top : 30px; margin-left : 30px; margin-right : 30px; text-align : center; border-radius : 50px; padding-top : 10px; padding-bottom : 10px; font-weight : 700; font-family : "Overpass", sans-serif; } <div class='circle'>1</div> <div class='circle'>2</div> <div class='circle'>3</div> <div class='circle'>4</div> <div class='circle'>5</div> <div class="btn">SUBMIT</div>Intenté poner un cheque con si el onclique era verdadero, se convertiría en falso, pero no obtuve el resultado deseado.
Si desea una lógica de selección/deselección, puede intentar configurar una clase cuando hace clic en un botón y eliminarla si vuelve a hacer clic.
Para ello existe el método toggle en la classList de los elementos (añade si no tiene la clase o la quita en caso contrario)
circles.forEach(c => { c.onclick = () => c.classList.toggle('selected') })Para cada círculo, alterne la clase 'seleccionada'. Cambié el nombre de círculo a círculos (es una colección de círculos).
PD: usar una clase en lugar de modificar el estilo en línea suele ser una mejor práctica.
const circles = document.querySelectorAll('.circle'); circles.forEach(c => { c.onclick = () => c.classList.toggle('selected') }) .circle { border-radius: 50%; width : 15px; height : 15px; padding : 10px; margin-left : 20px; display : inline-block; background : #262d37; color : #e7eaec; text-align : center; } .circle:hover { border-radius: 50%; width : 15px; height : 15px; padding : 10px; margin-left : 20px; display : inline-block; transition : 0.5s; opacity : 0.7; color : #e7eaec; text-align : center; } .btn { background-color: hsl(25, 97%, 53%); color : #e7eaec; margin-top : 30px; margin-left : 30px; margin-right : 30px; text-align : center; border-radius : 50px; padding-top : 10px; padding-bottom : 10px; font-weight : 700; font-family : "Overpass", sans-serif; } .circle.selected { background-color: hsl(25, 97%, 53%); } <div class='circle'>1</div> <div class='circle'>2</div> <div class='circle'>3</div> <div class='circle'>4</div> <div class='circle'>5</div> <div class="btn">SUBMIT</div>En lugar de esto:
const color = circulo[j] === el ? 'hsl(25, 97%, 53%)' : '#262d37'; circulo[j].estilo.backgroundColor = color;
Puede alternar la clase, por lo que tendrá
circle[j].classList.toggle(colorWhenClicked)Y en su archivo html tendrá un código similar,
<div class='circle basicColorClass'>1</div> <div class='circle basicColorClass'>2</div> <div class='circle basicColorClass'>3</div> <div class='circle basicColorClass'>4</div>Ahora en tu código css:
.basicColorClass{ color: #262d37; } .colorWhenClicked{ color: hsl(25, 97%, 53%); }Debe agregar una clase active para rastrear qué círculo está activo y luego podemos comparar con los círculos existentes para decidir agregar o eliminar una clase active .
También dejo algunos comentarios por esos cambios en Javascript, pueden checarlo.
const circle = document.querySelectorAll('.circle'); for (let i = 0; i < circle.length; i++) { const el = circle[i]; el.onclick = (e) => { //find the active circle const activeCircle = document.querySelectorAll('.circle.active')[0]; //if it's active, remove `active` class if (activeCircle) { activeCircle.classList.remove("active"); } //find the current clicked circle const currentCircle = e.target; //if the current clicked circle is different with the active circle //we add the `active` class to the current circle //if they're the same, we should not add the active class if (currentCircle !== activeCircle) { currentCircle.classList.add("active"); } } } const submit = document.querySelectorAll('.btn'); for (let i = 0; i < submit.length; i++) { const el = submit[i]; el.onclick = () => { for (let j = 0; j < submit.length; j++) { const color = submit[j] === el ? '#fff' : 'hsl(25, 97%, 53%)'; submit[j].style.backgroundColor = color; submit[j].style.color = 'hsl(25, 97%, 53%)'; } } } .circle { border-radius: 50%; width: 15px; height: 15px; padding: 10px; margin-left: 20px; display: inline-block; background: #262d37; color: #e7eaec; text-align: center; } .circle.active { background-color: hsl(25, 97%, 53%); } .circle:hover { border-radius: 50%; width: 15px; height: 15px; padding: 10px; margin-left: 20px; display: inline-block; transition: 0.5s; opacity: 0.7; color: #e7eaec; text-align: center; } .btn { background-color: hsl(25, 97%, 53%); color: #e7eaec; margin-top: 30px; margin-left: 30px; margin-right: 30px; text-align: center; border-radius: 50px; padding-top: 10px; padding-bottom: 10px; font-weight: 700; font-family: "Overpass", sans-serif; } <div class='circle'>1</div> <div class='circle'>2</div> <div class='circle'>3</div> <div class='circle'>4</div> <div class='circle'>5</div> <div class="btn">SUBMIT</div>