user2416594
user2416594

Reputation: 1

Using javascript to load a css hidden image as a background image on page loading

Noob at javascript and have searched without luck. Is it possible to use javascript to load an image which is already in the body of the html (css visibility hidden) to become visible as a background image in a div on page load?

Upvotes: 0

Views: 630

Answers (1)

Mithun Satheesh
Mithun Satheesh

Reputation: 27845

Yes.

Just do like

<script type="text/javascript">

      window.onload = function() {

          // get the image url from the src attribute of image
          imgurl =  document.getElementById("yourImgID").src;
          // set it as background to the div you want
          document.getElementById("yourDivID").style.background = "url("+imgurl+") no-repeat";

      }

</script>

You can see a sample fiddle here

Upvotes: 2

Related Questions