I have a desire to use Javascript to control CSS styles

Within the CSS code below, I am seeking to vary the size of a square randomly. This can be achieved using the Math.random() property in Javascript, but I am uncertain how to apply it to define the size in CSS.

 #square {
      width: 100px;
      height: 100px;
      background: red;
    }

Instead of fixed values for width and height, I desire them to be randomized. Additionally, I would like the position/orientation of the square to be random as well. This goes beyond simply generating random numbers; while that is part of the solution, it does not encompass the entire approach.

Answer №1

Here is the solution you've been waiting for!

let randomNumber = Math.random() * 500;
let widthValue = randomNumber.toString();
document.getElementById("square").style.width = widthValue + "px";
document.getElementById("square").style.height = widthValue + "px";
#square {
  background: red;
}
<div id="square"></div>

I hope this provided code snippet helps you with your project.

Answer №2

function generateRandomSize() {
  return Math.random()* 100 + 10 + "px";
}

for (var element of document.getElementsByClassName("random")){
  element.style.width = generateRandomSize();
  element.style.height = generateRandomSize();
}
#box1 {
  background-color: blue;
}

#box2 {
  background-color: red;
}

#box3 {
  background-color: green;
}
<div id="box1" class="random"></div>
<div id="box2" class="random"></div>
<div id="box3" class="random"></div>

Answer №3

If you're looking to randomly set both the height and width, you can try this method. However, if you want them to be the same, you can simply use the same random number:

reset();
function reset(){
    reset_square();
    reset_position();
}

function reset_square() {
    document.getElementById("square").style.width = Math.floor(Math.random() * 100) + 1 + "px"; 
    // generates a random number between 1 and 100

    document.getElementById("square").style.height = Math.floor(Math.random() * 100) + 1 + "px"; 
    // generates a random number between 1 and 100
}

function reset_position(){
    document.getElementById("square").style.top = Math.floor(Math.random() * 100) + 1 + "px"; 
    // generates a random number between 1 and 100

    document.getElementById("square").style.left = Math.floor(Math.random() * 100) + 1 + "px"; 
    // generates a random number between 1 and 100
}
#square{
    background-color: red;
    color: white;
    position: absolute;
}
<div id="square">This is custom size</div><br>
<button onclick="reset()">Reset</button>

I hope this explanation helps you with your coding needs :)

Answer №4

initialize();
function initialize(){
    setup_square();
    set_initial_position();
}

function setup_square() {
    document.getElementById("square").style.width = Math.floor(Math.random() * 100) + 1 + "px"; 
    // generates a random width value between 1 and 100 pixels

    document.getElementById("square").style.height = Math.floor(Math.random() * 100) + 1 + "px"; 
    // generates a random height value between 1 and 100 pixels
}

function set_initial_position(){
    document.getElementById("square").style.top = Math.floor(Math.random() * 100) + 1 + "px"; 
    // sets the square's top position to a random value between 1 and 100 pixels

    document.getElementById("square").style.left = Math.floor(Math.random() * 100) + 1 + "px"; 
    // sets the square's left position to a random value between 1 and 100 pixels
}
#square{
    background-color: red;
    color: white;
    position: absolute;
}
<div id="square">This is a customized square</div><br>
<button onclick="initialize()">Initialize</button>

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

unexpected automatic scrolling that occurs when hovering over an element

a sudden scrolling takes effect simultaneously with hovering on an element. What confuses me more is that it does not happen every time I hover over the element but just occasionally or maybe there is a specific scrolling position that I can't see yet ...

Developing an interactive input field using JavaScript's Document Object Model (DOM)

I am struggling with creating an editable text field using JavaScript. I have come across a function that allows for editing, but I am unsure if it is possible to change the title from High School to Middle School, which is generated by the function create ...

Problem with Internet Explorer version 9 and above and the Flip Card feature

I have a cool feature for one of my clients where clicking on one div causes another div to flip in its place, like a card flipping over. It's kind of like those portfolio image flippers, but instead of images, it flips divs with content inside. How ...

Activate an asynchronous request within a dropdown menu that was loaded using ajax

Let me start by presenting a simplified version of my code: HTML : <form id="add"> <select id="cat"> <option selected value="">…</option> <option value="a">A</option> <option value="b"& ...

Having trouble with the onClick function in React?

Here is my simple react code: Main.js: var ReactDom = require('react-dom'); var Main = React.createClass({ render: function(){ return( <div> <a onClick={alert("hello world")} >hello</a> </ ...

Display time series data from PHP by utilizing Flot Charts in jQuery

After receiving data from a database, which is formatted using PHP and returned as a JSON response for an Ajax call, I encountered an issue. Everything works fine and the data is plotted except when the X-Axis contains dates, in which case nothing gets plo ...

The use of fs.writeFileSync is invalid and will not work for this operation

Encountering an issue while working with fs in next.js, receiving the following error message: TypeError: fs.writeFileSync is not a function Here's a snippet from my package.json: resolve: { fallback: { "fs": false }, } ...

Using the power of Javascript's jQuery library: the fantastic ".on()" Event Handler

I'm encountering an issue with the Jquery Event Handler ".on()". On my home page, I have a Favorite button on each post. If the post has not been favorited: li appears inactive Event 1 is triggered If the post has been favorited: li appears act ...

The padding on the button inside the v-card is not being applied as expected

I am facing an issue with the following code snippet: <v-card height="200"> <v-card-actions class="mb-0"> <v-btn flat color="orange">Share</v-btn> <v-btn flat color="orange">Explore</v-btn> & ...

Replace the hyphen with a comma using JavaScript

Looking for a way to modify a string like this: "PALS español K- add-on" by replacing the - with ,. The desired output should be: "PALS español K, add-on" Is there a JavaScript solution to achieve this task? ...

drag items on your smartphone with ease

Hello everyone, I am looking to make items draggable on a smartphone as well. Here is my HTML code: <input class="inputText mb-2 border border-primary rounded" v-model="newTodo" @keypress.13='addTodo' placeholder="W ...

unable to display data through the web service

The functionality of this code is correct, but it seems to not be displaying records. When the record is retrieved from the file and shown in an alert, everything works fine. $j().ready(function(){ var result =$j.ajax({ ...

Issue: In an Angular electron app, a ReferenceError is thrown indicating that 'cv' is

I have been working on a face detection app using OpenCv.js within an Angular electron application. To implement this, I decided to utilize the ng-open-cv module from npm modules. However, when attempting to inject the NgOpenCVService into the constructor ...

Setting up a function in React to utilize an image stored in state

I have a function in my react component for image classification that retrieves the image from the img tag using document.getElementById: const img = document.getElementById('animal_image');. The image uploaded via the file input updates the sta ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

Create a speech bubble using only CSS, featuring a partially see-through background and a stylish border

I wish to design a speech bubble using only CSS. There are specific requirements I need to meet: It should adjust its size based on content with some padding or a set size. The background color must be semi-transparent. You must be able to define a borde ...

Tips for dynamically changing the class of a form field in jQuery when it is empty

I am currently working on a form that looks like this; <form id="myform" name="myform"> <input type="text" class="required" value="" name="qwer" /><br /> <input type="text" value="" name="asdf" /><br /> <input type=" ...

The functionality of ng-show becomes compromised when used in conjunction with ng-animate

Once the animate module is activated, the ng-show functionality seems to stop working. Even though the default value for the ng-show expression is set to false, the element is still displayed and the ng-hide class is not being applied. However, if I deac ...

Send a Date Object through an Event Emitter to be used in a Date Picker

I created a personalized Date Picker Child Component, and when the onDateChange event occurs, I intend to send an event to the parent component. @Output() selectedDateChange = new EventEmitter<Date>(); onDateChange($event) { this.selectedDateCha ...

How to arrange three buttons in a row using CSS styling

After reviewing similar issues posted by others, I have not found a solution to my problem. Despite trying the suggested solutions, I am unable to center two buttons representing different departments on my webpage. Here is my source code: <script ...