Struggling to align the image elements accurately

I am aiming to create a layout similar to the image displayed below.

To be more specific, my goal is to scatter smiley faces randomly within a 500px area while also having a border on the right side of the area.

However, with the current code I'm using, I'm not achieving the desired outcome.

<!DOCTYPE html>
<html>
<head>
    <style>
        img {
            position: absolute
        }

        div {
            width: 500px;
            height: 500px
        }

        #rightSide {
            position: absolute;
            left: 500px;
            border-left: 1px solid black
        }
    </style>
</head>
<body onload="generateFaces()">

<div id="leftSide"></div>
<div id="rightSide"></div>
<script>
    var numberOfFaces = 5;
    var top_position = 400;
    var left_position = 400;
    var theLeftSide = document.getElementById("leftSide");
    var i = 0;
    function generateFaces() {
        while (i < numberOfFaces) {
            var this_img = document.createElement("img");
            this_img.src = "#";

            this_img.style.top = top_position + "px";
            this_img.style.left = left_position + "px";
            theLeftSide.appendChild(this_img);
            top_position = top_position - 50;
            left_position = left_position - 50;
            i++;
        }
    }
</script>

</body>
</html>

The output I am currently getting from the provided code snippet appears like

What steps should I take to correct this?

Answer №1

By incorporating a while loop, you consistently reduce both the top and left positions by 50 in each iteration, ensuring equal spacing between images.

To introduce randomness, consider utilizing the Math.random() method which generates values ranging from 0 to 1. By scaling these values with the container's dimensions, you can achieve varied and unpredictable image placements.

Answer №2

If you need to generate random positions, simply use the random function. However, if you want fixed positions, you will need to implement specific position checks.

top_position  = Math.random()*400; left_position = Math.random()*400;

Check out this JS Fiddle for an example: https://jsfiddle.net/manishghec/13k8caen/

Answer №3

If you're looking to incorporate random positioning:

topPos = Math.random()*400; leftPos = Math.random()*400;
thisImage.style.top = topPos + "px";
thisImage.style.left = leftPos + "px";
leftContainer.appendChild(thisImage);

Check out the fiddle here: https://jsfiddle.net/v222wgav/1/

Answer №4

Here's a method to create random top_position positions and random left_position positions.

You have the freedom to adjust the code below according to your requirements.

I've integrated a random function called getRandom, which is basically a standard function for generating a random number within a specified range.

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

To utilize it, simply provide the minimum and maximum number of pixels within the desired range.

getRandom(0, 400);

var numberOfFaces=5;
var top_position = getRandom(0, 400);
var left_position = getRandom(0, 400);
var theLeftSide = document.getElementById("leftSide");
var i = 0;
function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function generateFaces()
{
  while(i < numberOfFaces)
  {
    var this_img = document.createElement("img");
    this_img.src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/718smiley.svg/60px-718smiley.svg.png";

    this_img.style.top = top_position + "px";
    this_img.style.left = left_position + "px";
    theLeftSide.appendChild(this_img);
    top_position = getRandom(0, 400);
    left_position = getRandom(0, 400);
    i++;
  }
}
img {
  position:absolute
}
div {
  width:500px;height:500px
}
#rightSide {
  position:absolute;
  left: 0px;
  top: 0px;
  border-right: 1px solid black
}
<!DOCTYPE html>
<html>
<body onload="generateFaces()">

<div id="leftSide"></div>
    <div id="rightSide"></div>
</body>
</html>


The #rightSide div can be removed completely like this:

var numberOfFaces=5;
var top_position = getRandom(0, 400);
var left_position = getRandom(0, 400);
var theLeftSide = document.getElementById("leftSide");
var i = 0;
function getRandom(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function generateFaces()
{
  while(i < numberOfFaces)
  {
    var this_img = document.createElement("img");
    this_img.src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fb/718smiley.svg/60px-718smiley.svg.png";

    this_img.style.top = top_position + "px";
    this_img.style.left = left_position + "px";
    theLeftSide.appendChild(this_img);
    top_position = getRandom(0, 400);
    left_position = getRandom(0, 400);
    i++;
  }
}
img {
  position:absolute
}
div {
  width:500px;height:500px
}
#leftSide {
  border-right: 1px solid black
}
<!DOCTYPE html>
<html>
<body onload="generateFaces()">

<div id="leftSide"></div>
</body>
</html>

Enjoy your Random Smilies!


Resources:

Image Credit:

How to use generate random numbers in a specific range

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

How to toggle code block visibility in Angular's ngOnInit() method

I'm currently analyzing different design patterns to optimize the number of REST calls when implementing a 'save while typing feature'. To provide a general overview, in my ngOnInit() function, I have included the following code snippet (wit ...

Developing a Vue.js application with a universal variable

In the previous version of Vue.js, 0.12, passing a variable from the root component to its children was as simple as using inherit: true on any component that needed access to the parent's data. However, in Vue.js 1.0, the inherit: true feature was r ...

Enhancing the Appearance of Legends in Chartjs

I'm attempting to customize the legend in my Chartjs chart, but I'm facing an issue where I can't seem to change the font color. What I want to achieve is having the font color in white while keeping the individual item colors intact in the ...

AngularJS: Solving the issue of controllers not exchanging data by utilizing a service

I am working with the following controllers and service: angular.module('myApp', []); angular.module('myApp').factory('ShareService', function() { var information = {}; information.data = ""; information.setD ...

Sending data using jQuery when a button is clicked

Is there a way to display the text from a text box when a button is clicked? Here's what I have been attempting: <script type="text/javascript> $(function() { $('#button').click(function(){ $.ajax({ type: "PO ...

Is there a way to efficiently display more than 10 data items at a time using the FlatList component in react-native?

Here is the data I am working with: singlePost?.Comments = [ 0: {id: 82, content: "Parent1", responseTo: null} 1: {id: 83, content: "Child1", responseTo: 82} 2: {id: 84, content: "Parent2", response ...

The href link on Android and iPhone devices is not activating, instead showing a focus rectangle

I've encountered an issue with the responsive layout of my HTML5 site on Android and iPhone versions. The links on the site are behaving strangely - they only work if I hold them down for a full second. Otherwise, they act as if a hover event is trig ...

Transform Django Model Instance from Serialized Back to Object using Ajax

Currently, I'm utilizing Ajax to search for a model instance. Once found, I return that instance and pass it as a variable to a template tag within my template. To achieve this, in my view, I serialize the object before sending it to the Ajax success ...

Personalized Pinterest button to link to a custom URL (Text Link, Image, or Both)

I've been searching for a solution without success. I'm looking to customize the image for my Pinterest (Pin It) button and pin a specific image by URL, not just the current page. Here is the custom link I created: <a href="http://pinterest. ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

submitting URL from dropdown menu without using the 'submit' button

My situation involves a dropdown list: @Html.DropDownList("InnerId", Model.GroupDropDownList, new { @class = "select_change" }) I am looking to achieve submitting the value when a user clicks on the selection without needing to select and then use a subm ...

Prevent user scrolling when full-screen menu is activated

Currently, I am developing a full-screen menu for a website and facing an issue with disabling the user's ability to scroll when the menu is open. Despite searching online, I have not found a suitable solution. It would be greatly appreciated if someo ...

Applying onclick css changes to a specific duplicate div among several others?

Recently, I encountered a situation where I have multiple identical divs on a page. <div class="class" ng-click="example()"></div> With the use of Angular 1.6.4 and jQuery, these divs are styled with background color and border color. Now, w ...

Discover the method to retrieve every element from a Listbox with the click of a Button and utilizing an ajax call

How can I retrieve all the elements from a Listbox when a Button Click event triggers an ajax call? I have created a function that successfully returns all the elements from the Listbox. However, when I try to bind it with the ajax call, it doesn't w ...

Is there a point in bundling NPM packages if they are ultimately going to be bundled by the project

I'm in the process of creating a TypeScript package for publication on NPM. My plan is to utilize this package in upcoming web development endeavors, most likely utilizing Vite. As I look ahead to constructing a future website with this module, I am c ...

Showcasing a variety of product titles with the help of CSS

Since the HTML is hosted on another server and I have no control over it, how can I use CSS to style certain list items? For example, The HTML on the server side: <ol> <li>Coffee</li> <li>Milk</li> <li>Orange Juice< ...

Assign a class to the checkbox of the first parent

I have a set of checkboxes generated using a for loop. I want the first checkbox to act as a parent, and all other checkboxes should act as children. When the parent checkbox is clicked, all child checkboxes should be checked. Although I have code to achi ...

Currently trapped within the confines of a Next.js 13 application directory, grappling with the implementation of a

I need to figure out how to export a variable from one component to layout.tsx in such a way that it is not exported as a function, which is currently causing the conditional check in the class name to always be true. Below is the code snippet: // File w ...

Incorporate npm libraries into vanilla JavaScript for HTML pages

Attempting to incorporate an npm package into plain JS/HTML served using Python and Flask. <script type="module"> import { configureChains, createClient } from "./node_modules/@wagmi/core"; import { bsc } from "./nod ...

How can two unique links toggle the visibility of divs with two specific IDs?

I am developing an interactive questionnaire that functions like a 'create your own adventure' story. The questions are shown or hidden depending on the user's responses. Below is the HTML code: <!-- TIER 3 ============================== ...