PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] Why style.backgroundImage returns empty?

 October 15, 2022     dom, javascript     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing