creating a randomized location within an HTML element using JavaScript

Trying to figure out how to randomly generate a position within an HTML div. I've come up with a JavaScript function that looks like this:

function randomInRange(min, max) {
    return(Math.floor((Math.random() * (max - min) + 1) + min));    
}  

My goal is to change the CSS of the div by setting random values for the left and top attributes (position:relative; left:0px; top:0px). The challenge lies in determining the appropriate min and max values for the function since the div uses percentage widths.

CSS of the div:

#stage {
    float: left;
    background-color: pink;
    width: 100%;
    height: 70%;
}

The function should trigger when a specific button is clicked

var button = document.getElementById("button");

button.onclick = function () {
    shape.style.left = randomInRange(0, stage.style.width);
    shape.style.top = randomInRange(0, stage.style.height);   
}
//The shape represents a circle div indicating the generated point

I've recently started learning JavaScript and am struggling to find a solution

Answer №1

The smallest possible values would be 0, while the largest values would depend on the width and height properties of the element being used. Read more about the different width properties here.

It is recommended to use element.outerWidth(true) and element.outerHeight(true).

Answer №2

let area = document.getElementById('area');
let areaWidth = area.offsetWidth;
let areaHeight = area.offsetHeight;

Feel free to utilize areaWidth & areaHeight in your custom functions

Answer №3

Opt for using clientWidth and clientHeight over width and height

button.onclick = function () {
    shape.style.left = randominrange(0, stage.style.clientWidth);
    shape.style.top = randominrange(0, stage.style.clientHeight);   
}

Here's the distinction between clientHeight vs offsetHeight

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

Tips for arranging two svg elements next to each other within a larger div

Hey everyone, I've been working on some HTML and JavaScript but I'm stuck on a basic issue. I have a simple code with a div containing two inner divs, each with an SVG element equal to the size of the parent div. My goal is to have these two inne ...

Issue with embedding icon within input field in Bootstrap version 4.1

I am currently implementing a project using Angular 6 along with the latest version of Bootstrap v4.1. I am attempting to create a reactive form with icons within input fields. As there is no direct way in bootstrap to place icons on the left side of input ...

Styling tables with borders in CSS

If a table is set to have a border at a high level, how can I ensure that classes inheriting from it do not have any borders set? table,td,th { border: 1px solid #0B6121; } How can I make sure that my other table has no borders at all? table.menu { ...

Changing links dynamically through jQuery

Below is the dynamicpage.js script: $(function() { var newHash = "", $mainContent = $("#main-content"), $pageWrap = $("#page-wrap"), baseHeight = 0, $el; $pageWrap.height($pageWrap.height()); ba ...

Incorporating the values of JavaScript objects into a global variable

I'm currently developing a bank account program and facing a challenge in adding my direct debits (DDs) into the global variable. When I create new objects using my constructor function and add them into the bank account, only the last created DD is s ...

Sharing parameters between functions in JavaScript

I have a working code but I want to modify the function getLocation to accept 2 arguments that will be passed to getDistanceFromLatLonInKm within the ajmo function. Currently, getDistanceFromLatLonInKm has hardcoded arguments and I would like to use variab ...

Building/Deleting the Vue Component using text search

In my App.vue file, I have the following setup: <template> <div id="app"> <input type="text" v-model="term"> <hello-world text="Button 1" v-if="term === ''"></hello-world> <hello-world ...

Updating and removing items from a React state using push and pop methods

I am working on a component in React and have the following state: this.state = { Preferences: [] } I am trying to push an element only if it does not already exist in the array to avoid adding duplicate elements. If the element is already ...

Display the initial x list items without utilizing ngFor in Angular 2

In the template, there are 9 <li> elements, each with a *ngIf condition present. It is possible that 5 or more of them may return true, but the requirement is to only display the first 4 or less if needed. Priority is given to the order of the < ...

Is it possible that the triangulation library functions on Firefox, but encounters compatibility issues on Chrome?

Currently, I am implementing triangulation using the Poly2Tri library. This is my code: var swctx = new poly2tri.SweepContext(contour); swctx.triangulate(); var triangles = swctx.getTriangles(); for (var w = 0; w < triangles.length; w++) { pts_t ...

Angular not functioning properly with alert windows

Here is a snippet of code where I am attempting to create an alert when a button is clicked: <!DOCTYPE html> <html> <head> <title></title> </head> <body ng-app> <button ng-click="alert('test')"> ...

Is the "sticky footer" in CSS causing issues with the percentage height of nested divs?

My "main-section" div is designed to inherit its height from the parent div, known as the "wrapper." The wrapper div, in turn, takes its height from the body of the document. Both the HTML and body tags are set with a height of 100%. To implement the ...

Performing calculations within handsontable

Trying to figure out how to concatenate values from a handsontable grid, I stumbled upon some code on jsfiddle that caught my eye. Here is the link: http://jsfiddle.net/9onuhpn7/4/ The task at hand involves 3 columns A,B,C and an attempt to concatenate ...

Tips for displaying Facebook comments with JavaScript

Can anyone help me figure out how to customize the data-href for Facebook comments using JavaScript (jQuery)? I tried incorporating the code below, but it's not displaying anything in the div col2. $("#col2").html( id+"<div class='fb-comm ...

Issue with consistent search autocomplete feature in a stationary navigation bar using bootstrap technology

My issue is with the autocomplete box - I want it to have the same width as the entire search box. Something like this using Bootstrap's col-xs-11 class: https://i.sstatic.net/npzhC.png If I set the position to "relative," it looks like this (all st ...

Combine the values of properties in an object

I have a JavaScript object that contains various properties with string values. I want to concatenate all the property values. Here's an example: tagsArray["1"] = "one"; tagsArray["2"] = "two"; tagsArray["Z"] = "zed"; result = "one,two,zed" To prov ...

What is the best method for removing table rows with a specific class?

I have an html table with several rows, and for some of these rows the class someClass is applied. My question is: How can I delete the rows that have a specific class? <table> <tr class="someClass"> ...</tr> <tr class="someClass"> ...

Unable to transmit the element identifier information through ajax

Whenever I attempt to pass id data through ajax, I encounter an undefined variable error. The ajax function works smoothly with form data, but the issue arises when trying to extract the id value. Below is the PHP/HTML code snippet: <ul class="sub-men ...

Utilizing PHP, Javascript, and jQuery in mobile technology gadgets

Can anyone recommend mobile technology products that have been developed using PHP, Javascript, and jQuery? What are the newest mobile products available on the market that have been built using these languages? Do popular devices like iPhone, BlackBerry ...

Interested in learning how to redirect to a different page using vanilla JavaScript after submitting an HTML form with a Django backend?

Recently delving into Django, I encountered a challenge of linking a js file to my HTML form page and saving the form data before moving on to the next screen. My aim was to incorporate a feature where users can click a picture and POST it along with their ...