Tengo varios marcos en mi html que se pueden arrastrar usando una función js. Están dispersos con valores únicos "izquierdo" y "superior" en CSS.
Quiero generar valores aleatorios izquierdo y superior cada vez que se carga/actualiza la página. Deben oscilar entre 10 y 1000 (px).
div CSS (tengo alrededor de 7 de ellos):
#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; }Left y top son lo que quiero aleatorizar para cada uno de los 7 o más divs que tengo.
Busqué algunos ejemplos de JS pero aún no he tenido éxito. A continuación se muestra un intento que no funciona:
$(function(){ var divClass = "div_"+Math.floor((Math.random() * 10) + 1); $('body').addClass(divClass); });intento 2:
$(document).ready(function() { $("body").css("left", "(" + Math.floor(Math.random() * (10)) ); });Los valores aleatorios se pueden generar y aplicar sin usar 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>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`; });$('document').ready(() => { // will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. const left = Math.floor(Math.random() * 991 + 10); // random int [10 - 1000] const top = Math.floor(Math.random() * 991 + 10); // random int [10 - 1000] $('#mydiv1').css({ 'left': `${left}px`, 'top': `${top}px` }); // styling the div });