What is the best way to ensure that my dynamically generated div shows up within the container div?

Web Development

<div id="container">
    <div id="wrapper">

    </div>
    <span id = "waveNum">Current Wave: 0</span>
    <input type = "button" value = "Start Game" onclick = "startGame()"></input>
</div>

<script src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script src="main.js"></script>
</body>

Javascript

var keyArray = [];
var currentWave = 1;


var player;
var player2;
function initiate(){
    player = new createPlayer(150,50,"player1","relative","blue"); 
    player2 = new createPlayer(150,0,"player2","relative","green");
}

function startGame() {
    point();
}

function createPlayer(l,t,id,pos,color){
    this.speed = 3;
    this.width = 25;
    this.height = 25;
    this.left = l;
    this.top = t;
    this.id = id;
    this.model = $("<div id=" + id + "/>")
        .css({"backgroundColor":color,"height":this.height,"width":this.width,
            "left":this.left,"top":this.top,"position":pos})

  $('#wrapper').append($(this.model));
}

function point(){ 
  leftP = parseInt(Math.random()*970);
  topP = parseInt(Math.random()*580);
  $points = $("<div class=point/>")
    .css({"backgroundColor":"yellow","height":"10px","width":"10px","left":0,
        "top":0,"position":"relative"})
  $('#wrapper').append($points)
}



function update(){
  //left
    if(keyArray[65]){
        var newLeft = parseInt(player.left)-player.speed+"px"
        player.left = newLeft;
        document.getElementById(player.id).style.left = newLeft;
    }
    //right
    if(keyArray[68]){
        var newLeft = parseInt(player.left)+player.speed+"px"
        player.left = newLeft;
        document.getElementById(player.id).style.left = newLeft;
    }
    //up
    if(keyArray[87]){
        var newTop = parseInt(player.top)-player.speed+"px"
        player.top = newTop;
        document.getElementById(player.id).style.top = newTop;
    }
    //down
    if(keyArray[83]){
        var newTop = parseInt(player.top)+player.speed+"px"
        player.top = newTop;
        document.getElementById(player.id).style.top = newTop;
    }

  //player2
    //left
    if(keyArray[37]){
        var newLeft = parseInt(player2.left)-player2.speed+"px"
        player2.left = newLeft;
        document.getElementById(player2.id).style.left = newLeft;
    }
    //right
    if(keyArray[39]){
        var newLeft = parseInt(player2.left)+player2.speed+"px"
        player2.left = newLeft;
        document.getElementById(player2.id).style.left = newLeft;
    }
    //up
    if(keyArray[38]){
        var newTop = parseInt(player2.top)-player2.speed+"px"
        player2.top = newTop;
        document.getElementById(player2.id).style.top = newTop;
    }
    //down
    if(keyArray[40]){
        var newTop = parseInt(player2.top)+player2.speed+"px"
        player2.top = newTop;
        document.getElementById(player2.id).style.top = newTop;
    }
    blockade();
    requestAnimationFrame(update);
}

function blockade(){
    var elemLeft = parseInt($('#wrapper').css('left'));
    var elemWidth = parseInt($('#wrapper').css('width'));
    var elemTop= parseInt($('#wrapper').css('height'));
  //blocks players from moving outside of game
    if(parseInt(player.left) + player.width >= elemLeft+elemWidth){
        player.left = elemWidth - player.width - 2;
    }
    if(parseInt(player.top) + player.height >= elemTop){
        player.top = elemTop - player.height - 2;
    }
    if(parseInt(player.top) < 3){
        player.top = 3;
    }
    if(parseInt(player.left) < 3){
        player.left = 3;
    }
    if(parseInt(player2.left) + player2.width >= elemLeft+elemWidth){
        player2.left = elemWidth - player2.width - 2;
    }
    if(parseInt(player2.top) + player2.height >= elemTop){
        player2.top = elemTop - player2.height - 2;
    }
    if(parseInt(player2.top) < 3){
        player2.top = 3;
    }
    if(parseInt(player2.left) < 3){
        player2.left = 3;
    }
}

window.onkeydown = function(page){
    keyArray[page.keyCode] = page.type === 'keydown';
}
    window.onkeyup = function(page){
        keyArray[page.keyCode] = page.type === 'keydown'
}

CSS

html, body {margin: 0; height: 100%; overflow: hidden}

#container{
    width:80%;
    height:60%;
    display: block;
    text-align:center;
    margin: 0 auto;
}
#wrapper{
    left:0px;
    width:1000px; /* 100% */
    height:600px;
    border:1px solid lime;
    margin:0 auto;
    background-color:black;
}

#player1, .point {
    float: left;
    clear: both;
}
body{
    background-color:black;
}
#waveNum{
    color:white;
    font-size:200%;
}

.point {
    overflow: auto;    
}

The point() function within the wrapper div is generating a random div but after several spawns, it starts to move out of the container. It appears that the container for the points might be shifting down over time, causing them to appear at the bottom and outside the intended area.

My goal is for all points to have the same initial top and left positions so that I can use the players to collect them by matching their positions. However, I am facing issues with getting them to share an origin point, which may be related to the positioning problems mentioned above.

Answer №1

To create a specific appearance for a div element, you can use the following CSS code:

z-index: 0;

Answer №2

To enhance the layout of your elements, consider applying absolute positioning to the wrapper div and relative positioning to the container div:

#container {
  position: relative;
}

#wrapper {
  position: absolute;
  top: 0;
  left: 0;
}  

By doing so, you remove the div from its normal document flow.

For further insight into why this method is effective, check out this resource.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the most effective way to retrieve cursors from individual entities in a Google Cloud Datastore query?

I am currently working on integrating Google Cloud Datastore into my NodeJS application. One issue I have encountered is that when making a query, only the end cursor is returned by default, rather than the cursor for each entity in the response. For insta ...

Best practices for handling errors with the async pipe

When it comes to async pipe error handling, is there a best practice that you follow? Should errors be handled in the service (even if it requires using global error handling) or is it more appropriate to handle them in the component? What approach do you ...

Tips for aligning two canvases with different heights at the top in HTML5

My problem involves two canvases housed within a single <div>. Despite their different heights, they are currently aligned at the bottom. +-------+ + + +-------+ + + + + + + +-------+ +-------+ Is the ...

A script that creates folders in Google Drive using a portion of the file name and organizes the files within

I require assistance in transferring files from a single Google Drive folder to folders named after the file names. The files come in two formats: .psd and .jpg. I am looking for a custom google.script that can identify the file name, create a folder base ...

Building a dynamic URL in ReactJS from scratch

const selectedFilters = { category: "", mealtype: "lunch", cuisinetype: "Italian", dishType: "Pasta" } const apiUrl = `https://api.edamam.com/api/recipes/v2?type=public&q=${query}&app_id=${app_id}&app_key=${app_key}`; User ...

Is it possible to have a TypeScript Reducer alongside JavaScript Reducers in my combineReducers function?

export default combineReducers({ todosReducer, calculatorReducer, dateReducer, }); I've encountered a challenge while trying to incorporate TypeScript into a portion of my extensive codebase. In the code snippet above, envision the first two reducers ...

Retrieve the attribute of the clicked element by utilizing the on click event handler

Within my HTML, there is a page displaying approximately 25 thumbnails, each with a like button in this specific format: <input type="button" class="btn btn-primary btn-small" id="likeBtn" data-id="545206032225604" value="Like"> It's important ...

What is causing the issue with using $("div[id*='\|']") in Internet Explorer 8 and 9?

section, have you encountered the issue where jQuery selectors fail to work with special characters escaped in IE8 and IE9? Presented below is the specific div that needs to be located: <div id="hello|12345"></div> The jQuery selector bein ...

Updating a singular value in an array using jQuery/JavaScript

Within a Javascript function, I have created an array called HM_Array1. The contents of the array are listed below: HM_Array1 = [[,11,147,,,,,,,1,1,0,0,0,1,"csiSetBorder(this)","null",,,true,["&nbsp;&nbsp;&nbsp;Accoun&nbsp;&nbsp;& ...

What could be causing the error when trying to use a PUT request with fetch in Vue?

Whenever I attempt to send a PUT request, an error pops up on the console. export function putUserData() { fetch(`${url}/user/${getCookie("ID")}`, { method: "PUT", headers: { "Authorization": `B ...

I'm baffled by the unexpected result I'm getting when using 'foreach' in node.js

Recently delving into node.js, I've encountered a puzzling issue. I'm perplexed as to why my output appears as: ciao data data instead of: data data ciao Below is the code causing this unexpected output: fs.readdir("sender", (err, fil ...

Significant distance between the content and the footer section of the page

Having trouble with a large gap between the content and footer ad on my website. I've tried to troubleshoot it myself, but suspect the issue may be related to the content generated by another site (indeed.com). Check out the link here: Any assistanc ...

Tips for linking server value with Javascript onmousedown in an aspx web page

I have a single Hyperlink on an aspx page. There are two tasks I need to accomplish: When I click on the hyperlink, I want to log some activity. While logging the EmployeeID value, I need to bind it from the server. However, I am encountering an error t ...

Switching the default image using jQuery upon click event

When I click on the image, I want to see a new image appear for just one second before returning to the default. I tried using setTimeout() function, but even after one second, I still see the same pressed.svg image. Here is my complete code: <html> ...

Transform an object in javascript to HTML format

Looking for a function to convert a JavaScript object of this type: {node: 'X', children: [{node: 'Y'}]} into a string resembling HTML. For instance, the example above should be transformed to something like: '<div class="X ...

Attempting to dispatch data from Vue.js event bus

I am attempting to increase the count of quotes by one and also add the text from a textarea to an array. While the text is successfully added to the array, the number of quotes always remains zero. I have tried combining the two actions in one method as w ...

Unable to refresh CSS file

Struggling with updating my website stylesheet. Everything seems to be in place - files uploaded correctly, cache cleared, even manually refreshed the CSS file multiple times. The only solution that works is renaming the CSS file and updating the link. A ...

Using the Enter key to submit HTML forms

I created a custom console using HTML, CSS, and JavaScript. The input doesn't show up when I press enter, I have to click the send button. How can I make it send on enter press? Here is the code, please assist me: /* code goes below*/ <!DOCTY ...

Ways to prevent html header content from being incorporated in jquery post outcomes

I've implemented jquery's "$.post()" function to insert a new list entry into the mysql database using php. $(document).ready(function(){ $(".theSubmit").click(function(){ var content = $("textarea").val(); var listn = $("in ...

Using ASHX to Return JSON in ASP.NET

I have implemented autocomplete functionality on my website. The JavaScript part is complete and I am able to retrieve the MembershipUser object of the matching user. Now, I need to format the JSON response as follows: { query:'Li', suggestio ...