Search code examples
javascriptcssimagerandomposition

Ho can I get these images to appear in random spots on the page?


I am creating a collage app that has an dogAPI. When the breed is selected a dog image will appear. I want the image to appear in a random spot on the page but ideally not over the text and dropdown menu. This is what I have tried and here is my codepen. This is an app so it needs to also be responsive.

    //Get a random number
let getRandomNum = (num) => {
    return Math.floor(Math.random() * Math.floor(num));
}

//show image in a random location
let moveImg = () => {
    let dogImgs = document.querySelector('.dogPic')
    let w = window.innerWidth;
    let h = window.innerHeight;
    dogImgs.style.top = getRandomNum(w) + "px";
    dogImgs.style.left = getRandomNum(h) + "px";
};

https://codepen.io/drxl/pen/VwbQZyK


Solution

  • Your moveImg function is flawed - it uses querySelector which will only select the first element. It should ideally accept an image as a parameter.

    We can declare it like so:

    let moveImg = (dogImgs) => {
        let w = window.innerWidth;
        let h = window.innerHeight;
        dogImgs.style.top = getRandomNum(w) + "px";
        dogImgs.style.left = getRandomNum(h) + "px";
    };
    

    Then, in your createImgs function, simply pass the constructed image as a parameter to moveImg.

    // fetches dog breed list/shows error if applicable
    async function start() {
        try {
            const response = await fetch("https://dog.ceo/api/breeds/list/all")
            const data = await response.json()
            breedList(data.message)
        } catch (e) {
            console.log("There was a problem fetching the breed list.")
            alert("There was a problem fetching the breed list.")
        }
    }
    
    
    //load breed list in dropdown menu
    start()
    function breedList(dogList) {
        document.getElementById("breeds").innerHTML = `
        <select onchange="loadByBreed(this.value)">
            <option>Choose a dog breed</option>
            ${Object.keys(dogList).map(function (breed) {
            return `<option>${breed}</option>`
        }).join('')}
        </select>
        `
    }
    
    //load images
    async function loadByBreed(breed) {
        if (breed != "Choose a dog breed") {
            const response = await fetch(`https://dog.ceo/api/breed/${breed}/images`)
            const data = await response.json()
            createImgs(data.message)
        }
    }
    
    //show randomized images
    function createImgs(images) {
        let imageContainer = $(".slideshow");
        let dogImgs = $('<img>');
        dogImgs.attr("src", images[Math.floor(Math.random() * images.length)]);
        dogImgs.addClass("dogPic")
        imageContainer.append(dogImgs);
        moveImg(dogImgs[0]);
    }
    
    //deletes pic if dbl tapped
    $(document).on('dblclick', ".dogPic", function () {
        $(this).remove();
    })
    
    //resets select menu when image has loaded
    $("#breeds").on("change", "select", function () {
        const value = this.value;
        console.log(value);
        let select = this
    
        setTimeout(function () {
            select.selectedIndex = 0;
        }, 800)
    });
    
    //Get a random number
    let getRandomNum = (num) => {
        return Math.floor(Math.random() * Math.floor(num));
    }
    
    
    let moveImg = (dogImgs) => {
        let w = window.innerWidth;
        let h = window.innerHeight;
        dogImgs.style.top = getRandomNum(w) + "px";
        dogImgs.style.left = getRandomNum(h) + "px";
    };
    body {
        font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
        background-color: rgb(26, 43, 38);
    }
    
    .header {
        text-align: center;
        color: white;
        font-size: 1.75rem;
        max-width: 80%;
        margin-top: 3rem;
    }
    
    
    select {
        font-size: 2rem;
        margin-bottom: 4rem;
        font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
        text-transform: capitalize;
        color: black;
        background-color: rgb(255, 255, 255);
    }
    
    .main-container  {
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    
    
    .slideshow {
        overflow: hidden;
        text-align: center;
    }
    
    
    
    img {
        max-width: 40%;
        margin-top: 25rem;
        position: absolute;
        left: 100px;
        top: 100px;
    }
    
    .top_link_position {
        display: block;
      position: fixed;
        bottom: 4%;
        right: 3%;
        z-index: 600;
      }
      
      
      .top_btn {
          border: 1.5px solid white;
          background: black;
          padding: .5rem .5rem;
          color: white;
          font-weight: bolder;
          text-transform: uppercase;
      }
    
    @media screen and (max-width: 425px) {
        .header {
            font-size: 1.25rem;
        }
        select {
            font-size: 1.5rem;
        }
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.3/css/all.css" integrity="sha384-SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk" crossorigin="anonymous">
        <!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> -->
        <link rel="stylesheet" href="styles.css">
        <title>Dog Collage</title>
    </head>
    <body>
        <!--Title and menu-->
    <div class="main-container">
        <div class="header">
            <h1>Dog Collage!</h1>
            <p>Select a dog and create your collage!</p>
            <p>Double-tap to remove an image.</p>
            <div id="breeds"></div>
        </div>
    </div>
    <div class="slideshow" id="imgs">
    </div>    
    
    <!-- Modal
    <div id="my-modal" class="modal fade" tabindex="-1" role="dialog"
    aria-labelledby="pokemonModalLabel"
    aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <h5 class="modal-title"  aria-labelledby="pokemonModalLabel">Modal title</h5>
            <button type="button" class="modal-close" id=".modal-close" data-dismiss="modal" aria-label="Close">X</button>
          </div>
          <div class="modal-body"></div>
        </div>
      </div>
    </div> -->
    
    <!--Top of Page Button-->
    <div  class="top_link_position">
        <a  class="back-to-top" href="#page_top" title="Top">
        <button class="top_btn"><span class="icon"><i class="fas fa-chevron-up fa-2x"></i></span></button>
        </a>
    </div>
    
    <script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
        <script src="src/index.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    </body>
    </html>