Reputation: 57
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>
Upvotes: 0
Views: 84
Reputation: 673
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.
Upvotes: 1