DEV Community

loading...
Cover image for My 30 days of Js journey: day 5

My 30 days of Js journey: day 5

Nirbhay Parmar
I am a budding web developer. Currently a grad student at Pandit Deendayal Petrolium University, Gandhinagar.
・1 min read

day 5

Today I learnt how to set style.backgroundImage property to dynamically change the background image of the div tag.

At first, I thought that it is a fair easy and straight forward task, but as it goes on I have to change my perception about the problem. I have to append the URL of an image to the empty URL property of the background-image CSS property.

Here is the HTML code of that div that i want to change the background-image:

<div id="image">Hover over an image below to display here.</div>

    <img
      class="preview"
      alt="Styling with a Bandana"
      src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg"
      onmouseover="upDate(this)"
      onmouseout="unDo()"
    />
Enter fullscreen mode Exit fullscreen mode

Here is my CSS code:

#image {
  width: 575px;
  height: 650px;
  border: 5px solid black;
  margin: 0 auto;
  background-color: #8e68ff;
  background-image: url("");
  background-repeat: no-repeat;}
Enter fullscreen mode Exit fullscreen mode

here is the javascript function to do the same:

function upDate(previewPic) {
  var Url = previewPic.src;
  document.getElementById("image").style.backgroundImage = "url(" + Url + ")";
  document.getElementById("image").innerHTML = previewPic.alt;
}
Enter fullscreen mode Exit fullscreen mode

In HTML there is a div which has a text in it. While it has some background-color. In my function, I want to change the background-color to a background-image with an image URL. So I have to concatenate the image URL.

This was done as a part of my Coursera course on web design.

Discussion (0)