Issue
So here is the HTML
<button class="w drum">w</button>
<script src="index.js" charset="utf-8"></script>
And This is the CSS
.w {
background-image: url("images/tom1.png");
}
.a {
background-image: url("images/tom2.png");
}
.s {
background-image: url("images/tom3.png");
}
.d {
background-image: url("images/tom4.png");
}
.j {
background-image: url("images/snare.png");
}
.k {
background-image: url("images/crash.png");
}
.l {
background-image: url("images/kick.png");
}
Lastly this is the javascript
for (let i in document.querySelectorAll(".drum")) {
document.querySelectorAll(".drum")[i].addEventListener("click", handleClick);
}
function handleClick() {
var url = this.style.backgroundImage;
console.log(url);
}
So when I click on w / a / s / d / etc. button, Console should return the image url right?
But this is what happened...
Console log shows empty string
Why is it empty??? Plz help
Solution
Use NodeList.prototype.forEach() and Window.getComputedStyle
const handleClick = (evt) => {
const url = getComputedStyle(evt.currentTarget).backgroundImage;
console.log(url);
}
document.querySelectorAll(".drum").forEach((elDrum) => {
elDrum.addEventListener("click", handleClick);
});
Answered By - Roko C. Buljan Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.