0

I am trying to have a function to change the background image URL in a div (see below). It shows net::ERR_FILE_NOT_FOUND in the console when running. Does the new image have to be hosted locally?

<html>
  <head>
    <script> 
      function changeback() {
        var x = document.getElementById('im').value;    
        document.getElementById('containerH').style.backgroundImage = 'url(img/'+x+')';
      }  
    </script>
  </head>
  <body>
    <textarea id="im" onKeyUp="changeback();" onKeyPress="changeback();"></textarea>
    <br>
    <div id="containerH" style="background-image:url(https://thejasfiles.files.wordpress.com/2015/07/summerholidays-heading.jpg); width:200px; height:400px; margin-left: 12%; margin-top: -2%;">
    </div>
    </div>
  </body>
</html>
Rich Churcher
  • 7,361
  • 3
  • 37
  • 60
ycd
  • 57
  • 5
  • 1
    It doesn't have to be hosted locally, but you have part of a url path hard coded there in the changeback function. – James Jan 04 '18 at 20:11

1 Answers1

1

It is because of the 'url(img/'+x+')'; value. img/ is a relative path to the current page and therefore it will try to lookup the image locally inside the relative 'img' folder.

<html >
<head>
<script> 
function changeback() {
     var x = document.getElementById('im').value;  
           document.getElementById('containerH').style.backgroundImage = 'url(' + x + ')';
       
  } 
  
</script>
</head>
<body>
<textarea id="im" onKeyUp="changeback();" onKeyPress="changeback();"></textarea><br>
<div  id="containerH" style="background-image:url(https://thejasfiles.files.wordpress.com/2015/07/summerholidays-heading.jpg); width:200px; height:400px; margin-left: 12%; margin-top: -2%;">
</div>
</div>
</body>
</html>

See this other post about the difference between relative and absolute paths.

  • Thank you very much, Richy! Can I please also ask what the "+" sign before and after the var are really used for? Thanks! – ycd Jan 04 '18 at 22:12
  • The "+" are used to concatenate values in Javascript. The backgroundImage[1] only accept a string. So in your case, if `x = "https://exemple.com/image.png"` It will become `...backgroundImage = 'url(https://exemple.com/image.png)';` [1]: https://www.w3schools.com/jsref/prop_style_backgroundimage.asp – Ricky Notaro-Garcia Jan 04 '18 at 22:34