Home > Software design >  Changing background of div in JavaScript
Changing background of div in JavaScript

Time:03-08

my code have one div and three picture my main task is to show the same image in div when I hover over any picture what I am not able to understand is how can I do it with variables so that if in future if add more pictures it does not make any problem for me note:: I want to do it by using variables I don't want to hard code image source. I am also attaching the image for reference only.

function showproperties(element) {
  var x = document.getElementById("box001");
  x.innerHTML = element.alt;
  var y = element.src;
  document.getElementById("printsrc").innerHTML = y;
  x.style.backgroundImage = y;
}
<body>
  <div id="box001">main hover box

  </div>
  <div >
    <div >
      <img src="img01.jpg" alt="Image 001" onm ouseover="showproperties(this)" onm ouseleave="defaulttext(this)">
    </div>
    <div >
      <img src="img02.jpg" alt="image 002" onm ouseover="showproperties(this)" onm ouseleave="defaulttext(this)">

    </div>
  </div>

</body>

image

CodePudding user response:

I tried to reproduce your issue and made some changes in it. I Hope that's how you wanted it to work. I have used some gif images url for demo purpose.

HTML:

       <div id="box001" style="width: 100px;height: 100px; margin:7px">main hover box
      
        </div>
        <div >
          <div >
            <img src="https://c.tenor.com/Lvhj4QVL8-4AAAAS/server-is-for-javascript.gif" alt="Image 001" onm ouseover="showproperties(this)" onm ouseleave="defaulttext(this)">
          </div>
          <div >
            <img src="https://c.tenor.com/FIcvxhgc1sgAAAAS/dit-is-een-code-blok-code.gif" alt="image 002" onm ouseover="showproperties(this)" onm ouseleave="defaulttext(this)">
      
          </div>
        </div>
      

JS:

var x = document.getElementById("box001");

function showproperties(element) {
  var y = element.src;
  x.innerText = "";
  x.style.backgroundImage = `url(${y})`;
}

function defaulttext(element) {
  x.innerText = "main hover box";
  x.style.backgroundImage = "none";
}

Full working code is available on this fiddle - https://jsfiddle.net/0h1urctn/

  • Related