I want the element to be highlighted only when "8k" is pressed not the other buttons,
I know querySelectorAll
is the key but don't know what change to make?
Beginner here. Thanks
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 >
<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 >
<img src="../pics/-vine-3404474.jpg" id="c4">
<img src="../pics/-alina-vilchenko-4550659.jpg" >
<img src="../pics/-ceejay-talam-8836293.jpg">
</div>
CodePudding user response:
Your dance
function is passed an event object when the click occurs, which has a currentTarget
property that is the element that the handler was attached to that caused the event.¹ So you can check if it's the 8k
button and only do the highlighting when it is.
With your current HTML, you could do that with the text content or 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)
}
...but I would add a class or data attribute to the element instead:
<button href="C4" style="order:1">8k</button>
Then
if (event.currentTarget.classList.contains("do-highlight")) {
That same value is also available as this
, but using the event.currentTarget
property lets you not worry about what this
value your function is called with.
CodePudding user response:
At the javascript level, there are small changes. When you click on the button you get an event object.
function dance(e) {
if(e.target.innerHTML=="8k"){
image.classList.add('highlight');
timeoutID = setTimeout(() => {
image.classList.remove('highlight');
clearTimeout(timeoutID);
}, 1000);
}
}