creating div elements that are confined within the visible area of the browser

I'm currently attempting to append a specific number of div elements to the body without altering the width or height of the body itself. Essentially, I need the new divs to remain within the viewport. Here is the code I'm working with:


divAmount = 6;
$(document).ready(function(){
windowWidth = $(window).width();
windowHeight = $(window).height();

game();

$('body').css({
    "max-width" : windowWidth,
    "max-height" : windowHeight 
    });
});

function game(){ 
for (var i = 0; i < divAmount; i++) {
        $("<div class='box' />").appendTo("body").css({
            "margin-left" : Math.floor(Math.random() * windowWidth - 100) + 1,
            "margin-top" : Math.floor(Math.random() * windowHeight - 100) + 1
        });
}

$('.box').click(function(){
    $(this).removeClass('box').addClass("exploding");
}); 
};  

While the current code correctly adds the divs, they are unfortunately not staying within the viewport.

Answer №1

Check out this working snippet I put together - http://codepen.io/Jk7R5/

By giving the .square elements absolute positioning, they appear to take up minimal space.

.square {
    background: blue;
    height: 15px;
    width: 15px;
    position: absolute;
}

Although, like someone mentioned earlier, it's recommended to create a container div with the dimensions of the window, rather than the body, and then set the body to 100% of the height and width. (This is how I set it up in the snippet)

Answer №2

To ensure proper control over width, consider applying the following CSS styles:

min-width: 120px;
max-width: 240px;

By setting these values, you can regulate the width of elements. You can also manage the height of the body tag in a similar manner.

Using this approach, any new div elements will flow seamlessly within the body without disrupting the overall layout.

For setting the min-width, min-height, max-width, and max-height, you can utilize screen.width and screen.height as references.

Need to stay within the viewport?

If you wish to prevent scroll bars, consider adding the overflow property to the body tag, although this may not be ideal in all cases.

Opt for using min and max values for maintaining consistency in sizing.

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

Mastering the art of utilizing absolute positioning with respect to the parent element

When creating an HTML report, there may be a requirement for rows to have elements printed on the same line with only absolute left positions specified at design time. It is desired that each row appears on the next line after the previous row without exp ...

Invoking the .html(result) function multiple times within the AJAX success callback

I have implemented this code in my template to handle my ajax request: <script> $(document).ready(function() { $("#send-mail-button").click(function(e){ e.preventDefault(); var nameVar = $('#name&apo ...

Is there a way to dynamically change the class of rows in jQuery datables based on a given condition?

I am working with jquery DataTables in conjunction with CodeIgniter to present data on a listing page. I am wondering how I can alter the class of a particular field based on certain conditions. Specifically, I have a status field where if the status is e ...

Is it possible to use jQuery to set a value for a form control within an Angular component?

I'm currently working on an Angular 5 UI project. In one of my component templates, I have a text area where I'm attempting to set a value from the component.ts file using jQuery. However, for some reason, it's not working. Any suggestions o ...

The scrollbar will be visible only when the mouse hovers over the table

I have been experimenting with customizing the scrollbar appearance of an ant design table. Currently, the scrollbar always displays as shown in this demo: https://i.stack.imgur.com/vlEPB.png However, I am trying to achieve a scroll behavior where the sc ...

What is the purpose of pressing the button a second time once the Conditional Statements are no longer

$(function() { $("button").click(function() { if ($(this).text() === "3") { console.log("correct"); $(this).text("correct") } else { console.log("wrong"); $(this).text("wrong") } }) }) <script type="text/javascri ...

Convert a prototype code to jQuery using AJAX syntax

Seeking advice on my code syntax as I transition from Prototype to jQuery. I currently have both frameworks running simultaneously and aim to streamline all scripts into jQuery for improved page load efficiency and speed. Migrating from Prototype to jQue ...

How can you enable fullscreen for a featherlight iFrame?

I have implemented Featherlight to display an iframe within a popup modal on my website. If you click the iframe button, you can see a demo of how it works. One issue I am facing is that the generated iframe tag by Featherlight does not include allowfulls ...

Exploring the power of combining Django with Bootstrap's tab view feature

Struggling to incorporate tabs using Django and Bootstrap. Despite changing the URL, tab switching isn't working correctly. Looking for guidance on how to switch tabs seamlessly. Code <div class = "company-info-tab"> <d ...

Exploring anchor hover effects and navigating adjacent sibling elements

Consider this html structure: <p><a></a></p> <div><a><img></a></div> To hide all images inside a div after a p tag, you can use the following code: p + div {display:none;} However, attempting to sho ...

An image appears fractured when placed within a table cell, yet displays perfectly when positioned outside of the table

I am currently facing an issue with loading image files in table cells using jQuery. Here is the code snippet from my View: <table id="personDataTable" border="1"> <tr style="font-size:large; height:auto"> <th width="10 ...

Looking for assistance in designing a responsive web page with CSS, specifically in determining the optimal page width

Currently, I am working on making my web page responsive for four different screen sizes (320px, 640px, 980px, and 1024px). Everything looks great and adapts well when I resize the site up to 1024px. However, once the size goes beyond that, I want to preve ...

Calculate the total cost for each row in a table by multiplying the quantity and price using jQuery, then display the result

I'm encountering an issue with my table row calculations involving price and quantity. The calculation results show up correctly in the console, but when I try to display them back on the table, the total sum of the first row gets duplicated into all ...

What is the optimal approach to composing this? [jQuery - Top Recommendations - if statement]

SharePoint 2013 is the platform I am currently working on, and within it, there are some (.aspx) pages with specific titles. I have developed a script that examines the title of the current page. If it matches any of the predetermined query titles, then i ...

Customizing Material UI Popover CSS classes within a Select component in a React application

I have integrated the Material UI Select component into my React project. I am attempting to customize the CSS classes .MuiPaper-root and/or .MuiMenu-list. This is how my Select component looks: <Select value={selectValue} disableUnderline onCha ...

What is the best way to reveal a concealed "div" when hovering the mouse over it?

Currently in the process of developing a dropdown menu to house a search engine form within a static menu bar. The desired functionality is for the search form to appear upon hovering over the "search icon." However, it seems that the submenu fails to disp ...

Selecting items with checkboxes in a Bootstrap dropdown menu

As I work on customizing a bootstrap dropdown with checkboxes, my goal is to have the label name written on the input dropdown in between ';' whenever a checkbox from the dropdown is selected. This will create a similar result as shown in the upl ...

Angular 10: A guide to dynamically highlighting navbar elements based on scrolling position

I am currently working on a single-page application using Angular 10. I have a simple page layout and I want to implement a feature that will highlight the navbar based on the scroll position. How can I achieve this functionality in a single-page applicati ...

Show and hide a div with the click of a button

As I embark on rebuilding a website from the ground up, I find myself pondering how to achieve a specific functionality: My goal is for another view to appear when one of two buttons is clicked. How can this be accomplished? I attempted the following app ...

Manage the application of CSS media queries using JavaScript

Is there a method to control which CSS media query a browser follows using JavaScript? As an example, let's say we have the following CSS: p { color: red; } @media (max-width: 320px) { p { color: blue; } } @media (max-width: 480px) { p { col ...