setting the background Size of div tag not working using Javascript

866 Views Asked by At

I need to change the size of a background image during an animation but it doesn't work.

Here is a simple version of my code:

document.querySelector("#Box").backgroundSize='cover';
#Box {
  background-image: url(https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg);
  width: 220px;
  height: 220px;
    }
  <div id="Box"></div>

4

There are 4 best solutions below

0
On BEST ANSWER

You should target the .style

document.querySelector("#Box").style.backgroundSize='cover';
#Box {
  background-image: url(https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg);
  width: 220px;
  height: 220px;
    }
  <div id="Box"></div>

0
On

You were missing the .style declaration in your query selector

document.querySelector("#Box").style.backgroundSize='cover';
#Box {
  background-image: url(https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg);
  width: 220px;
  height: 220px;
    }
<div id="Box"></div>

0
On

Just missing style from your js...

document.querySelector("#Box").style.backgroundSize='cover';
#Box {
  background-image: url(https://beebom-redkapmedia.netdna-ssl.com/wp-content/uploads/2016/01/Reverse-Image-Search-Engines-Apps-And-Its-Uses-2016.jpg);
  width: 220px;
  height: 220px;
    }
<div id="Box"></div>

0
On

The #Box element have no backgroundSize property. You should just refer to its style property and then to backgroundSize

document.querySelector("#Box").style.backgroundSize = 'cover'