Home > Net >  How to set background image of div using an unsplash api image?
How to set background image of div using an unsplash api image?

Time:01-26

So I am trying to make a full screen background of an image from unsplash api but I cant seem to change the background image url of the div when I do document.getElementById("image").style.background = 'url("data["results"][0]["urls"]["regular"]")';. But if I dont use a div and use img instead, it works but I cant make it full screen. Anyone know any fixes for this?

Here is my code:

js

fetch("https://api.unsplash.com/search/photos?query=philippines&client_id=2BHRf_91BeuRTt7CDCE-_eA3l95wlZLWlyog-KQ2c2Y")
    .then(
        function(response){
            console.log(response);
            
            if(response.status !== 200){
                console.log("There was a problem. Status code: "   response.status);
                return;
            }

            response.json().then(
                function(data){
                    document.getElementById("image").style.background = 'url("data["results"][0]["urls"]["regular"]")';
                }
            )
        }
    )
    .catch(
        function(err){
            console.log(err '404');
        }
        )

html

<html>
    <head></head>
        <link rel="stylesheet" href="style.css">
        <body>
           <!-- <div class = "image_container"> -->
               <div id = "image"></div>
            <!-- <img id="image"></img> -->
           </div>
        </body>
        <script src="requests.js"></script>
    </head>
</html>

css

*{
    padding: 0;
    margin: 0;
}

#image{
    height: 100vh;
    background-image: url();
    background-size: cover;
    background-repeat: no-repeat;
}

CodePudding user response:

You forgot some " on your url().

Here is an example:

fetch("https://api.unsplash.com/search/photos?query=philippines&client_id=2BHRf_91BeuRTt7CDCE-_eA3l95wlZLWlyog-KQ2c2Y")
    .then(
        function(response){
            
            
            if(response.status !== 200){
                console.log("There was a problem. Status code: "   response.status);
                return;
            }

            response.json().then(
                function(data){
                    document.getElementById("image").style.background = 'url('   data["results"][0]["urls"]["regular"] ')';
                }
            )
        }
    )
    .catch(
        function(err){
            console.log(err '404');
        }
        )
*{
    padding: 0;
    margin: 0;
}

#image{
    height: 100vh;
    background-size: cover !important;
    background-repeat: no-repeat !important;
}
<div id = "image"></div>

  •  Tags:  
  • Related