Struggling to align the image elements accurately

I am aiming to create a layout similar to the image displayed below.https://i.sstatic.net/Q5n8J.png

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 likehttps://i.sstatic.net/aG1ET.png

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

React is choosing to re-render only one of the setState functions, neglecting the other

I'm currently in the process of developing a basic Tic Tac Toe game using React. The Objective: Each button in the game has its own state. When a button is clicked, it should change from ' ' to an 'X' and update the player's ...

What is the method to modify an action in an Ajax function?

I am trying to modify the action in the AjaxUpload function. The issue is that the value of setnamefile in the action does not change because the page does not reload. My idea was to change the action on submit, but I have not been able to do so successfu ...

Is there a specific CSS selector that targets elements with "multiline" content?

My website has a menu that displays with the following CSS: a { background:red; } <a href="#">Home</a> <a href="#">Downloads</a> <a href="#">Contact</a> <a href="#">FAQ</a> <a href="#">Disclaimer&l ...

The hover effects cease before the cursor is even shifted

Can someone explain why the hover effect stops before the mouse is moved off the element? I implemented the hover effect on a before pseudo element. ...

Transform a string (variable) into an object using JSON.parse, encountering an unexpected token error

I am struggling with parsing a string variable back to an object. Despite searching through various posts on this issue, I have not found a solution that works for me. if(subMatch.match(/\{.*\}/)){ /// new Object of some sort var o ...

Aligning variable width numbers within a div container

Currently experimenting with CSS to create a calendar design that mimics the look of a traditional paper calendar. One issue I've encountered is the alignment of numbers within boxes, especially when dealing with double digits. When displaying a sing ...

Connect the checkbox input to the text input

I'm facing an issue where I need to tie a checkbox input to a text input in my form. Here's the scenario: I am extracting data from a database. The primary key data serves as the value for the checkboxes. When a checkbox is selected, it should ...

Looking to convert a jQuery function to plain JavaScript code?

Struggling with my homework, I must apologize for any mistakes in my English. My task involves creating a chat using node.js and I found some code snippets on a website "" which I used successfully. The issue now is that the chat relies on old jQuery libr ...

I am encountering difficulties with a nodejs query where I am unable to successfully include the "+" symbol as part of the query

Every time I submit a query for B+ or A+ {{URL}}/api/help/?bloodType=B+ it ends up showing as empty space, like this. Is there a way to properly pass the "+" sign in the query? Thanks. P.S: _ works fine. {"bloodType":"B "} ...

Oops, seems like there was a problem with parsing the

I have encountered an issue when trying to decode the value of a PHP array sent as JSON format. Here is how I created the array: $ads = $atts['ads']; if (sizeof($ads) > 0) { foreach($ads as $social_item) { $sdbr = $social_ ...

Retrieving the caret's position in TinyMCE 4

Is there a way to retrieve the caret position in pixels (x & y dimensions) in TinyMCE 4 without obtaining row/column numbers? It should be relative to anything and achieved without adding any extra tags like bookmarks. Anyone know if TinyMCE has a method f ...

Having difficulty transitioning Express Controller logic to a Service Class

Within the User Controller, there is a function that processes a GET request to /user/ and retrieves two JSON objects randomly from a MongoDB collection. Here is how the response looks like inside the controller: [{ "name": "User 1" ...

Using JavaScript to fetch elements by their ID along with a button

UPDATE: I have corrected the semi-colons, case sensitivity, and brackets in the code. It functions properly if I eliminate the functions after buttonPARTICULAR! Why is that? UPDATE: Issue resolved. My mistake. Apologies!!! :-Z When I simplify it like thi ...

The hyperlink tag doesn't respond to clicks in Safari, yet functions properly in all other web browsers

I'm encountering an issue with my header drop-down menu in Safari—it works perfectly in Chrome, but when I try to open the drop-down menu in Safari, it's unresponsive. Clicking on it does nothing, preventing me from accessing other drop-downs. ...

Display the invoice bill using text in a Vue component

Hello, I am looking to print an invoice that resembles the one shown in this picture https://i.sstatic.net/6mzwe.jpg However, when I try to print it, I get a different output with some additional elements https://i.sstatic.net/uaKZC.jpg I am using vue. ...

Avoiding line breaks when submitting data through Ajax calls is achievable by using the `.val` method

I've come across multiple articles discussing ways to add line breaks to the .val in jQuery, but unfortunately none of them have worked for me. I attempted using the recommended workaround provided by jQuery: $.valHooks.textarea = { get: function( ...

Issues with tangents in three.js compared to the VertexTangentsHelper with problems on display

After enabling the "vertexTangentsHelper" feature in THREE.js, I've noticed that the tangents on various geometries appear to be incorrect. I'm questioning whether these tangents are being miscalculated (possibly due to my shader output) or if t ...

Is it possible to prioritize CSS selectors in a specific sequence?

I possess a pair of div elements: div class="one two three" div class="three two one" Is it probable to formulate a CSS regulation that exclusively focuses on ".one.two.three" and does not encompass ".three.two.one" ? ...

Ensure that the footer remains at the bottom of the webpage, without being positioned as fixed

I am encountering an issue on my work2 Website where the footer is not staying at the bottom of the page when there is limited content. I have searched extensively on Google, YouTube, and CSS tricks for a solution, but have not found one that works for my ...

Using AngularJS variables within JavaScript code

This is my introduction to using AngularJS. The code snippet below displays the desired output: <a href="http://www.example.com/xyz/{{life.animal}}/" target="_blank">Hello </a> Upon clicking, it redirects to: http://www.example.com/xyz/c ...