Creating unique CSS styles through randomly generated values for both the left and top positions each time the page is refreshed or loaded

I have multiple draggable frames within my HTML, each with unique "left" and "top" values in the CSS. I am looking to randomize these values every time the page is refreshed or loaded, with a range of 10 to 1000 pixels.

Here is an example of the CSS for one of the divs:

#mydiv1 {
    position: absolute;
    z-index: 0;
    width: 250px;
    height: 250px;
    top: 400px;
    left: 500px;
    background-color: black;
    border: 2px solid #e8ff26;
    text-align: center;
    box-shadow: 2px 2px 4px #888888;
    cursor: move;
}

The goal is to randomize the "left" and "top" values for all divs on the page, not just one.

I have tried some JavaScript examples without success. Here is an example of one attempt that didn't work:

$(function(){
    var divClass = "div_" + Math.floor((Math.random() * 10) + 1);
    $('body').addClass(divClass);
});

Another unsuccessful attempt:

$(document).ready(function() {
    $("body").css("left", "(" + Math.floor(Math.random() * (10)) );
});

Answer №1

One can easily generate and implement random values in their code without relying on JQuery

const myDiv = document.querySelector("#mydiv1");

const randomLeftValue = Number.parseInt(Math.random() * (1000 - 10) + 10);
const randomTopValue =  Number.parseInt(Math.random() * (1000 - 10) + 10);


myDiv.style.top = `${randomLeftValue}px`;
myDiv.style.left = `${randomTopValue}px`;
#mydiv1 {
    position: absolute;
    z-index: 0;
    width: 250px;
    height: 250px;

    background-color: black;
    border: 2px solid #e8ff26;
    text-align: center;
    box-shadow: 2px 2px 4px #888888;
    cursor: move;
}
<div id="mydiv1">

</div>

Answer №2

When the DOM content is loaded, this script randomly positions an element with the ID 'mydiv1' on the page.
    
    document.addEventListener("DOMContentLoaded", function(event) { 
        let item = document.getElementById('mydiv1');
        let rng_top = Math.floor(Math.random() * 1000);
        let rng_left = Math.floor(Math.random() * 1000);
        item.style.top = `${rng_top}px`;
        item.style.left = `${rng_left}px`;
    });

Answer №3

$('document').ready(() => { // This code will only execute once the DOM (Document Object Model) of the page is fully loaded and ready for JavaScript to run.

const leftPos = Math.floor(Math.random() * 991 + 10); // Generate a random integer between 10 and 1000

const topPos = Math.floor(Math.random() * 991 + 10); // Generate a random integer between 10 and 1000

$('#mydiv1').css({ 'left': `${leftPos}px`, 'top': `${topPos}px' }); // Apply styling to the div based on the randomly generated positions 

});

Answer №4

I'm a little bit puzzled about your end goal, but based on my understanding, you are looking to achieve the following: generate a random integer between 10 and 1000, and then apply random left and top values for each frame wrapper (referred to as 'frame' here).

const generateRandomInteger = (max = 1000, min = 10) => {
  return Math.round(Math.random() * (max - min) + min) + "px";
}

$(function () {
  $('.frame').each((index, element) => {
    $(element).css({top: generateRandomInteger(), left: generateRandomInteger()});
  });
});

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

Exploring ways to retrieve boolean values with Angular and PHP

I am currently learning Angular and PHP and I am trying to make some modifications to the tutorial found at . Specifically, I want to change the second value to a checkbox and retrieve its value using both Angular and PHP. However, I am encountering an iss ...

Using Ajax/jQuery in combination with Mongodb

My experience with Ajax/jQuery is fairly new. I am currently working on creating a sample HTML page using Ajax/jQuery to retrieve all customers and search for a customer by ID. Each customer has three variables: ID, firstName, and lastName. I am looking t ...

ngPrime table column selection and data extraction

I am looking to extract multiple columns from a table. Can anyone suggest the best approach for this? Does NGPrime offer any functionality for achieving this task? Appreciate your help! ...

Using Linq to Transform Rows into Columns

I have a table that looks like this: ID Attributes Value 1 Name Jason 2 Age 14 3 Address 12 Test Road A linq query has been created to select each value based on its ID from p in db.p ...

When the border width is set to 1px in FireFox, the border size is calculated as 0.667

When using the FireFox browser alone, I noticed that the border size is displayed as 0.6667 when setting the border width to 1px on a div, input element, or any HTML element. The same issue occurs whether the border is applied using inline CSS or a separat ...

Achieving Center Alignment of Two Elements with Varying Widths in Relation to the Parent Container, all while maintaining Left Alignment and consistent indentation

I am currently working with Material UI, but maybe this is just a matter of understanding how to achieve it with Flexbox. Something similar to what is shown in the image below. I am struggling to make all three lines align in the same way on different scre ...

Is there a way to intercept all AJAX requests in JavaScript?

Could there be a universal event handler for ajax requests that is automatically triggered upon the completion of any ajax request? This is something I am exploring while developing a greasemonkey script for an ajax-heavy website. In past scripts, I have ...

What could be causing my HTML footer to not grow from its borders?

Hello there, I need assistance with an HTML document I am working on. Can you explain why my footer is not expanding to the edges even though I have set the width to 100%? Please help. Please note that the code provided is incomplete, and for the full cont ...

An array of size 10x10 where each new array replaces the previous one

I'm currently working on a function that generates a 10 by 10 array filled with random D's and E's. Below is the code snippet: function generateTenByTenArray(){ var outerArray = []; var innerArray = []; for(var i = 0; i < 10 ...

How about passing some vue props data over?

I am trying to assign different colors based on the percentage of each of the 5 batteries. However, the issue I'm facing is that the color spread is not specific to each individual battery. I suspect this issue arises because the bmss data is being r ...

Element in list displaying a distinct alignment from the rest

I currently have a navigation bar based on a list, which looks something like this: https://i.stack.imgur.com/e1Dmb.png My concern is how to position the "Logout" item on the right side of the screen. I've tried adding clear list items but that seem ...

Production environment poses a challenge as Rails 4 struggles to locate fonts

Situation: I am facing an issue with my Rails 4.0.0 application deployed using capistrano, where the asset precompilation does not work properly on my production server. Challenge: Despite successfully adding a font and using it with @font-face locally, t ...

I am having trouble getting the filter functionality to work in my specific situation with AngularJS

I inserted this code snippet within my <li> tag (line 5) but it displayed as blank. | filter: {tabs.tabId: currentTab} To view a demo of my app, visit http://jsfiddle.net/8Ub6n/8/ This is the HTML code: <ul ng-repeat="friend in user"> ...

Why is my Navbar defaulting to be located inside the "./components/Index" folder?

https://i.sstatic.net/5v8IZ.pngI recently created a 'Navbar' component inside the 'components' directory and used a separate index file.js to export it to App.js. However, when I try to import it, it ends up inside the 'components/ ...

Adjust the div container to wrap underneath the image if the webpage width decreases

Hello there, I am currently in the process of creating my own portfolio. I have a brief introduction that I would like to display next to an image of myself, with the image positioned on the right side. I have a div called "container" which contains anoth ...

Trouble encountered with card flip style login form in Vue.js, as the card is not maintaining its position properly during transition animations

Need help styling a login/signup component in Vue.js where flipping between the two cards isn't working smoothly. The transition is causing one card to move down and right while the other comes in from the bottom right. It's hard to explain the i ...

Having trouble with the scrolling feature on a read-only text area within a form

My form allows users to input their data, but once submitted, the form becomes read-only. However, I'm facing an issue where the data in the text area is not scrollable even though it should be. I need assistance in figuring out why the content in th ...

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 ...

What scenarios call for utilizing "dangerouslySetInnerHTML" in my React code?

I am struggling to grasp the concept of when and why to use the term "dangerous," especially since many programmers incorporate it into their codes. I require clarification on the appropriate usage and still have difficulty understanding, as my exposure ha ...

Updating Socket.io with multiple data emissions upon refresh or reload

I'm facing an issue that is very similar to this problem: https://github.com/rethinkdb/rethinkdb/issues/6503 Whenever I connect for the first time, it only logs once. Upon refreshing, it logs twice. Subsequent refreshes result in an additional log ea ...