1

Want to fetch an image using javascript from CSS URL so I can style the background image with background-size: cover and colour. The code is used for simply Fast Image Loading With Javascript

var image = document.images[0]
var bigImage = document.createElement("img")
   bigImage.onload = function () {
    image.src = this.src
}
setTimeout(function () {
    bigImage.src = "img/large.jpg";
}, 50)
.header-image {
  padding: 200px 100px;
  background-color: #eee;
  background-size: cover;  
  height: 75vh; 
}
<img id="image" class="header-image" src="img/small.jpg" width="1200" />

        
  • 1
    Please, clarify your question. What do you mean by fetch? What is your desired result? – Calvin Nunes Aug 02 '18 at 19:13
  • still not understanding... which CSS image? Your code doesn't show any CSS with image, url, linear-gradient... nothing like that. Edit your question, rebuild your way of asking because currently it's hard to get what you want – Calvin Nunes Aug 02 '18 at 19:25
  • I think I understand your question. You just want to be able to adjust the placement of the image in the element more specifically than the standard `` tag allows, so you're trying to adjust the `background` properties to do so. – Chase Ingebritson Aug 02 '18 at 19:28
  • Sorry for not being clear I want to get rid of then somehow get the imge from css url this way I can add style to the background image – Shaf Mohammed Aug 02 '18 at 19:29
  • Yes that what I want to do – Shaf Mohammed Aug 02 '18 at 20:25

1 Answers1

0

The src of the <img> is actually the foreground content of the <img> (as explained here). So, if you set the background-image of an <img> as well as the src, the src will just override the background-image.

In this case, I would recommend you just set the background-image of a <div>.

var url = "https://images-na.ssl-images-amazon.com/images/I/51IwmuOPQyL._SL1052_.jpg";
var element = document.querySelector('.example');
element.style.backgroundImage = "url(" + url + ")";
.example {
  width: 100px;
  height: 100px;
  
  background-color: black;
  background-size: cover;
}
<div class="example"></div>
Chase Ingebritson
  • 1,559
  • 1
  • 12
  • 25