Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass background:url dynamically using javascript to css?

See the css below and I would like to change the "background:url" part dynamically using javascript.

div{
    background: url('pinkFlower.jpg') no-repeat fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    width:100vw;
    height:100vh;
    top:0;
    left:0;
    float:left;
}

I tried the same by passing below javascript

document.querySelector('div').style.background= "url('pinkFlower.jpg') no-repeat fixed";

and this results against my purpose of the original css.

Can someone help me fixing this?

Thanks in advance.

like image 808
Mahesh Babu Avatar asked Apr 10 '26 04:04

Mahesh Babu


1 Answers

I think this should work :

document.querySelector('div.image').style.backgroundImage = 'url("your/url/to/the/file")';

Edit : Trick : if you're on Chrome, launch webdev panel (F12) and in the console write console.log(document.querySelector('div.image').style)

You will get all attributes of the "style" object, which you can then change as you want

like image 71
Dan Chaltiel Avatar answered Apr 12 '26 17:04

Dan Chaltiel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!