DEV Community

Cover image for My 30 days of Js journey: day 5
Nirbhay Parmar
Nirbhay Parmar

Posted on • Updated on

My 30 days of Js journey: day 5

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>

      alt="Styling with a Bandana"
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)