Creating a series of random div elements each time the page is loaded

Can I share a quick little story with you? I recently created a page (super simple - just two divs with different background images, check it out here.)

Now here's the kicker: I want to make it so that every time a new page loads, those two divs appear in a random order, filling the entire screen content. No predictable pattern, just a beautiful chaos of randomness. Think of it as a massive grid where the divs keep shuffling around with no set order.

So my burning question is...is this even possible? Would I need to delve into PHP for something like this? I'm clueless when it comes to PHP, so any guidance would be greatly appreciated!

Thanks everyone for your help in advance!

Answer №1

http://jsfiddle.net/aBjMx/

JavaScript with jQuery

var element1 = '<div class="first">';
var element2 = '<div class="second">';

var totalElements = Math.floor(window.innerWidth/30)*Math.floor(window.innerHeight/30);

for (i = 0; i < totalElements; i++) {   
    if ( Math.random() > 0.5 ) {
        $(element1).appendTo('body');
    }
    else {
        $(element2).appendTo('body');
    }
}

CSS styling

div.first, div.second {
    height:30px;
    width:30px;
    float:left;
}

div.first { background-color:#AABBCC; }
div.second { background-color:#DDEEFF; }

Update: replaced screen.availWidth with window.innerWidth

Answer №2

How about creating elements like this? Simply loop through as many times as needed and dynamically add elements.

for (i = 0; i < 300; i++) {
    var box1 = document.createElement("div");
    var box2 = document.createElement("div");
    box1.innerHTML = "box1";
    box2.innerHTML = "box2";
    box1.setAttribute("class", "box1");
    box2.setAttribute("class", "box2");
    document.body.appendChild(box1);
    document.body.appendChild(box2);
}

Answer №3

You don't need PHP for this task. Simply utilize client-side scripting with Javascript (consider Jquery for simplicity).

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

Is it possible for OrbitControls to maintain rotation based on model origin even while panning?

Let me illustrate my question through an image: Shown here is the top view from the camera, with a grey cube representing a 3D model. The 'X' marks the center of rotation, while the arrow indicates the direction of rotation: Typically, when p ...

Is it possible to modify the background color of a select option menu when hovering over it?

It turns out that the default background color of the select option menu changes to blue when it is hovered over. However, I would like to personalize and adjust it to my preference using Bootstrap 5 and CSS. Any assistance with this customization would ...

Custom JSON filtering

I have a JSON object called Menu which contains various menu items for my system that I am developing using VueJS + Vuetify. I need to filter these menu items based on the "text" field, regardless of position in the text and without differentiating between ...

The .on() function in Jquery seems to be malfunctioning when it comes to handling dynamically

Despite my efforts to find a solution after exploring other questions and attempting various possible fixes, I am still unable to correctly bind the click event. Any assistance would be greatly appreciated. My current project involves a webpage that intera ...

Calculate the total number of table rows added using jQuery

I am seeking help to identify the error in my code. My goal is to count the number of table rows added by the end user and display an alert box if the row count is not equal to 2. Below is my HTML code: <table width="100%" border="0" cellspacing="0" c ...

Querying escape characters from JSON to JavaScript

When trying to stringify quotes (' and "), it is necessary to escape them. However, the following results in Firebug can be puzzling: 1. >> JSON.stringify({foo: "a"a'a'}); SyntaxError: missing } after property list Interpretation: Th ...

Updating the value of a JSON data attribute

I am looking to update a specific value in a JSON array. To provide more context, here is the DOM structure I have: <input class="fileupload" type="file" data-form-data='{"table_reference": "data_monitoring", "table_token" : "X43sd"}'> I ...

Expanding across the entire horizontal space, excluding any space allocated for

I've been on a quest to find a solution for my unique problem, but all my efforts have been in vain so far. Currently, I'm working on developing a mobile website and facing a challenge with the input boxes. Despite wanting them to take up the en ...

Tips for arranging Bootstrap thumbnails in a horizontal row

Could someone assist me with arranging Bootstrap thumbnails side by side instead of vertically stacked? Any advice is appreciated! Here is the current code snippet for the two thumbnails: <div class="row"> <div class="col-sm-6 col-md-4"& ...

The quirky behavior of JavaScript's Array.reduce

Here is a snippet of code: let data = [1, 2]; let newBody = {}; let newArray = data.reduce((acc, current) => { newBody.doc = current; acc.push(newBody); return acc; }, []); The resulting array is: newArray = [ { doc: 2 }, { doc: 2 } ] If I re ...

Using Selenium in Java: Implementing a line break in a webpage and executing it

On the current page, I need to insert a <br> tag into a specific section. The HTML code below shows where I want to make this addition: <p style="font-size:13pt; line-height:130%; margin:0pt; orphans:0; text-align:center; widows:0"> <span c ...

Are there specific Dojo treegrid restrictions to prevent the display of the "Oops, an error occurred" message?

I have run into an issue with my Dojo treegrid JSON store. It works perfectly with a small number of items, but fails when handling thousands of items. I am wondering if there are any limitations on the number of items or childItems in the store, or if t ...

"Error message: The server tag within the OnClientClick attribute is not properly formed

In the HTML code, there is the OnClientClick attribute set to evaluate if IsActive is true before triggering a confirmation message for removing the control from Brand-Mappings. Unfortunately, this is currently causing a server tag not formed error. Any a ...

When the page is resized, the Font-Awesome icons shift position

/* icon sect*/ .social { margin-top: px; padding: 0; position: absolute; top: 60%; left: 50%; transform: translate(-50%,-50%); } .social li { list-style: none; float: left; margin: 0px; width: 60px; height: 10px; line-height: 60px; ...

Hidden Span Element Appears Invisible

I have the following span element in my HTML: <span style="float: right;color: red; display: inline-block;" id="antcl_error"></span> However, when I checked its visibility it returned as not visible: $(document.body).find("#antcl_error").is( ...

Why does my body feel devoid whenever I submit a post request from the React JS frontend?

Angular js: export const addUser=( username, email )=> { return (dispatch) => { fetch("http://yourdomain.com/addUser", { method: "post", credentials: 'same-origin', mode: 'no-cors', ...

ng-bind-html not refreshed following ng-click triggering

Recently, I started learning about the MEAN stack. I have implemented an ng-repeat in my HTML code that displays a list of titles. Each title has an ng-click function attached to it, which is supposed to show more details in an overlay popup. blogApp.co ...

Unspecified variable in AngularJS data binding with Onsen UI

I am new to Onsen UI and AngularJS, and I have a simple question about data binding. When I use the variable $scope.name with ng-model in an Onsen UI template, it returns as UNDEFINED. Here is my code: <!doctype html> <html lang="en" ng-app="simp ...

Storing the AJAX response in an external variable using jQuery callback function

I'm struggling to set a variable with the results of an ajax query. I understand that I can't just return the result in the success function due to its asynchronous nature. However, I'd like to achieve this using a callback function without ...

Make the text area occupy the full width of the remaining screen space

I've been struggling to make the text area fill the remaining width of the screen. Everything is set up nicely, but I just can't seem to find a solution to get it to expand and occupy the rest of the available space. I intentionally refrained fr ...