Assign JavaScript variable as the value for styling

I am looking to create a unique webpage where text appears in various random locations each time the page is loaded. To achieve this, I need to set the left and top distances of a DIV element containing text at random positions on the page. The code snippet provided below gives an overview of my initial idea:

<body>
    <script>
        function generateRandomCoordinates() {
            var leftValue = Math.round(Math.random()*1000);
            var topValue = Math.round(Math.random()*1000);
        }
        window.onload = generateRandomCoordinates;
    </script>
    <div style="left:leftValue; top:topValue;">
        <p>Test</p>
    </div>
</body>

How can I apply variables to the CSS style of a DIV element?

If you have any alternative methods for creating a dynamically relocating DIV, please share them as well. Thank you!

Answer №1

Modify the style properties of an element using JavaScript:

<head>
    <style>#myElement {position: absolute;}</style>
</head>
<body>
    <script>
        function changeStyle() {
            var newLeft = Math.random()*800;
            var newTop = Math.random()*800;

            var target = document.getElementById('myElement');

            target.style.left = newLeft + 'px';
            target.style.top  = newTop + 'px';            
        }
        window.onload = changeStyle;
    </script>
    <div id="myElement">
        <p>Example</p>
    </div>
</body>

Answer №2

Take a shot at something similar to this:

<body>
    <script>
        function changePosition() {
            var leftPos = Math.random()*1000;
            var topPos = Math.random()*1000;
            var myDiv = document.getElementById('mydiv');
            myDiv.style.left = leftPos + 'px';
            myDiv.style.top = topPos + 'px';
        }
        window.onload = changePosition;
    </script>
    <div id='mydiv'>
        <p>Test</p>
    </div>
</body>

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

Updating Bootstrap variables

According to the documentation of Bootstrap, Sass variables in Bootstrap 4 come with the !default flag which allows you to override the variable's default value in your own Sass without modifying Bootstrap's source code. You can copy and paste va ...

Employing PHP to verify the activation of a CSS stylesheet in an if/else statement

Is there a way to determine if a specific stylesheet is loaded in order to run different code based on its presence? For example: // Create loop counter $counter = 0; while ( have_posts() ) { // MaxIT - Shows 2 listings per loop instead of 1 for ( ...

Retrieving PNG image from dynamically created PDF file with DomPDF

Having trouble displaying an image on a generated PDF using DOMPDF. My DomPDF version is v2.0.3 and I'm working with XAMPP on localhost. This is the output: see image here Below is the code snippet: <?php require_once __DIR__ . '/vendor/auto ...

Utilizing JQuery to track DIV clicks

I am encountering an issue with DIV clicks while using JQuery. I need guidance on this problem. Within my HTML, there are three designated DIV elements: <html> <body> <div id="overviewContainer"> <div id="firstContainer"></ ...

Can Angular-Material help create a sidenav that toggles on and off?

I am struggling to create a side menu that remains closed by default on all screen sizes and always opens on top of other content. Despite my efforts, it keeps switching at widths over 960px. This is the current code for my menu: <md-sidenav is-locked ...

Hide button for the last input form to dynamically remove in jQuery

At first, I hide the remove button when there is only one form. However, if there are multiple forms and the user deletes all of them, I want the last form to remain visible and not be deleted. Can someone assist with this issue? Here is my code: <! ...

Implementing the delete functionality in a mongoose model and displaying the result in an object page using mongo

I am currently facing an issue where I am unable to delete a specific 'ticket' from the database. The webpage shows a table listing all the tickets with their respective seat names and prices, along with a delete button (form). However, when I tr ...

Concealing a tab within a WordPress site

We have integrated a portfolio plugin with 4 categories, but we want to hide the All tab that is being displayed along with them. In order to achieve this, we need to include additional JavaScript in the header like so: (function($, undefined) { $(func ...

What is preventing me from accessing React state within Tracker.Autorun?

I'm feeling lost on this one. I have implemented a Tracker.autorun function to monitor when my Mongo subscription is ready for querying (following the advice given in this previous Meteor subscribe callback). It seems to be working fine as it triggers ...

What is the best method for styling the "body" of multiple pages in a React.js application to prevent them from overlapping?

Hello everyone, After attempting different approaches in numerous ways, I have turned to the experts here who are sure to have the answer to this simple problem. The issue at hand is that when I try to apply background images and other properties to the ...

Angular 4.0 has discontinued the use of the ngGetContentSelectors() method

There has been a deprecation of the method ngGetContentSelectors() in Angular 4.0. Can you suggest an alternative for this? ...

Promise.allSettled() - Improving resilience through retry mechanisms for concurrent asynchronous requests

TL;DR: I'm seeking advice on how to handle multiple promise rejections and retry them a specified number of times when using Promise.allSettled() for various asynchronous calls. Having come across this article: I was intrigued by the following state ...

Simple method for displaying or hiding divs depending on the status of a selected radio button using CSS only

I am currently working on showing or hiding div elements based on the status of a radio button. These divs are located after the input buttons in a different section of the page, and I am facing challenges in referencing them accurately. This code is for ...

How can we use forEach on an array or JSON data while sorting by the most recent date?

How can I reverse the order of data in the "forEach" loop so that the latest date is displayed first instead of the oldest to newest? var json = { // JSON data goes here } json.TrackingRecord.MovementInformation.Movement.reverse().forEach(function(it ...

jQuery is unable to retrieve the parent element of a dynamically generated element as it returns as undefined

I have created login and registration forms using ajax calls to send data. The server side of the application is built with Flask, and any errors are returned in JSON format. In the success function of the ajax call, I create an <li> element that dis ...

What is the best way to include various audio tracks from my array list?

I am looking to implement multiple audio tracks for a single video file, similar to the example provided in this link https://codepen.io/eabangalore/pen/NZjrNd (they are using their own custom JavaScript with videojs) Here is the list of sound tracks that ...

Tips for programmatically choosing a text range within CKEDITOR stages?

Issue: In my JavaScript code, I have a CKEditor instance like this: var editor = CKEDITOR.instances["id_corpo"]; I am looking to programmatically insert some text and then select a specific text range within the editor. So far, I have successfully inse ...

JavaScript encountered an error stating "phone is not defined" due to an uncaught ReferenceError

Whenever I click on the Phone Number, it displays an error message saying that the function is not defined. How can I fix this issue? Thank you in advance! Here's the code snippet: <div class="product-label"> <h4><?php echo $p["Fu ...

How to identify an element based on the text content of the element that follows it using XPath

I am working with this specific piece of HTML code <div class="a-expander-content a-spacing-base a-expander-inline-content a-expander-inner a-expander-content-expanded" style="" aria-expanded="true"> <form id="pp-yT-23" class="pmts-add-cr ...

Header text refuses to cooperate and center itself

Struggling to find the best way to center the "Header" text while keeping the icon in place. I've tried using text-align: center;, but it's not producing the desired results. Could anyone provide guidance on how to achieve this? Thanks. IMG: ...