Home > Software design >  How to know if an element is going outside of a grid-container
How to know if an element is going outside of a grid-container

Time:01-25

I am creating a simple project with a character and grid template. The idea is, when the character is moving, to move the grid template.

HTML File:

<html>
<head>
    <script defer src="main.js"></script>
    <link rel="stylesheet" href="main.css">
</head>
<body>
<div >
    <img id="inFront" src="inFront.png" width="200px">

    <div id="insideBox" > 
        <div id="pageOne" ></div>
        <div id="pageTwo" ></div>
        <div id="pageThree" ></div>
        <div id="pageFour" ></div>
        <div id="pageFive" ></div>
        <div id="pageSix" ></div>
        <div id="pageSeven" ></div>
        <div id="pageEight" ></div>
        <div id="pageNine" ></div>
    </div>

</div>
</body>
</html>

and css:

img {
    position: absolute;
    z-index: 99;
}

body {
    overflow-x: hidden;
    overflow-y: hidden;
    width: 100vw;
    height: 100vh;
}

.box {
    width: 99vw;
    height: 99vh;   
    background-color: gray;
    z-index: -1;
}

.insideBox {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr;
    width: 300vw;
    height: 300vh;

    position: relative;

}

So, in this case, we have the div box and inside box we have another div, called insideBox. insideBox is a grid container with 9 child elements. I have a JS file which detects user input (W A S D) and allows me to move my character around the page.

Once the character hits the bottom of the viewpoint, the container (insideBox) changes it's position. Please look at this: enter image description here

And here is my problem: I can go outside that div insideBox (the gray color on the .gif means that I am outside the grid). How can I make it so, if I go outside the grid nothing would change? So, it is not possible for my character to go outside insideBox

CodePudding user response:

In this case it is best to check the offsetLeft and offsetTop of the character and compare it to the offsetLeft and offsetTop of the container (taking into account the width/height as well) to determine which container the character is inside. Reference: http://www.javascriptkit.com/domref/elementproperties.shtml

  • Related