0

HTML

<body>
    <form class="ipform">
        <label>CAM IP :</label>
        <input type="url" id="ip_cam">
        <input type="button" id="connectBtn" onclick="getIp()" value="CONNECT">
    </form>
    
    <script src="js/script.js"></script>
</body>

CSS

body {
  overflow: hidden;
  box-sizing: border-box;
  background-color: #1f1f29;
  background-image: url("https://images.unsplash.com/photo-1606851361385-9a2ead6ce3ab?ixid=MXwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=751&q=80");  
  background-repeat: no-repeat;
  background-size: cover;
  background-size: 100% 100%;
  background-attachment: fixed;
}

JS

function getIp() {
  var x = "url('";
  var y = document.getElementById("ip_cam").value;
  var z = "')";
  var xyz = x + y + z; //"url('" get from y "')
  document.body.style.backgroundImage = xyz;
}

Inserting url of an image in the input box, the background image changes.
Now, for a invalid link how to set a default background-image
background-image have to use as CSS property not as div in html
Randomly tried with these code below.But Nothing happened.I'm not so familiar with JavaScript Can you please help..

// function myFunction() {
//   document.body.style.backgroundImage = "url('assets/error3.gif')"
// }
// if(   document.body.style.backgroundImage.onerror = null )

// {
//   myFunction();
// }
// document.body.style.backgroundImage.addEventListener("error", myFunction);

1 Answers1

0

if you add the second url to background-image attribute, if the first one not loaded then the second one will load.

function getIp() {
  var x = "url('";
  var y = document.getElementById("ip_cam").value;
  var z = "'), url(assets/error3.gif)"; //added here with comma
  var xyz = x + y + z; 
  document.body.style.backgroundImage = xyz;
}
mehmetx
  • 850
  • 6
  • 6