Quiero que el elemento se resalte solo cuando se presiona "8k", no los otros botones, sé querySelectorAll
es la clave, pero no sé qué cambio hacer. Principiante aquí. Gracias
JavaScript
const image = document.getElementById("c4"); let timeoutID; document.querySelectorAll(".side-nav button").forEach(item => item.addEventListener("click", dance)); function dance() { image.classList.add('highlight'); timeoutID = setTimeout(() => { image.classList.remove('highlight'); clearTimeout(timeoutID); }, 1000) }
CSS
.highlight { box-shadow : 0 4px 8px 0 rgba(218, 51, 119, 0.4), 0 6px 20px 0 rgba(0, 0, 0, 0.19); }
HTML
<div class="side-nav"> <button href="#" style="order:3">2k</button> <button href="#" style="order:2">4k</button> <button href="#" style="order:4">1080p</button> <button href="C4" style="order:1">8k</button> </div> <div class="column"> <img src="../pics/-vine-3404474.jpg" id="c4"> <img src="../pics/-alina-vilchenko-4550659.jpg" > <img src="../pics/-ceejay-talam-8836293.jpg"> </div>
A su función dance
se le pasa un objeto de evento cuando se produce el clic, que tiene una propiedad currentTarget
que es el elemento al que se adjuntó el controlador que causó el evento.¹ Entonces puede verificar si es el botón 8k
y solo resaltar cuando es.
Con su HTML actual, podría hacerlo con el contenido de texto o href
:
function dance(event) { if (event.currentTarget.textContent === "8k") { // or: if (event.currentTarget.getAttribute("href") === "C4") { image.classList.add('highlight'); } timeoutID = setTimeout(() => { image.classList.remove('highlight'); clearTimeout(timeoutID); }, 1000) }
... pero en su lugar, agregaría una clase o un atributo de datos al elemento:
<button href="C4" class="do-highlight" style="order:1">8k</button>
Después
if (event.currentTarget.classList.contains("do-highlight")) {
Ese mismo valor también está disponible como this
, pero usar la propiedad event.currentTarget
le permite no preocuparse por this
valor con el que se llama a su función.
A nivel de javascript, hay pequeños cambios. Cuando hace clic en el botón, obtiene un objeto de evento.
function dance(e) { if(e.target.innerHTML=="8k"){ image.classList.add('highlight'); timeoutID = setTimeout(() => { image.classList.remove('highlight'); clearTimeout(timeoutID); }, 1000); } }