Why is my image not being positioned randomly, even though the random function is functioning correctly?

I've been attempting to create a matching game, where images are randomly positioned on the left and right sides. Despite using the random function, which is functioning correctly (confirmed with console.log), my images are not appearing in a random order, rather in a straight line.

Below is a snippet of my javascript, css, and html code....

var numberOfFaces=5;
var theLeftSide=document.getElementById("leftSide");
var imgHeight=80;
var imgWidth=80;

function generateFaces(){
while(numberOfFaces>0){
var smileImg=document.createElement("img");

smileImg.src="http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
smileImg.style.height=imgHeight + "px";
smileImg.style.width=imgWidth + "px";
var randomTop=Math.random() * 400;
randomTop=Math.floor(randomTop);
console.log(randomTop);
var randomLeft=Math.random() * 500;
randomLeft=Math.floor(randomLeft);
console.log(randomLeft);
smileImg.style.top= randomTop + "px";
smileImg.style.left=randomLeft + "px";
leftSide.appendChild(smileImg);
numberOfFaces--;
}

}
body{
margin:50px;

}
p{
text-align:center;
font-size:18px;
}

#outer{
border:0.5px solid black;
position:realtive;
height:500px;
margin:20px;
}


#rightSide,#leftSide{
width:500px;
height:500px;
position:absolute;
}

#rightSide{
 left:700px;
 border-left:2px solid black;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="MatchingGame.css" media="screen" />
<script type="text/javascript" src="MatchingGame.js" ></script>
<title>Matching Game</title>
</head>
<body onload="generateFaces()">
<p>Click on the extra smiling face on the left side.</p>
<div id="outer">
<div id="leftSide"></div>
<div id="rightSide"></div>
</div>
</body>
</html>

Answer №1

The default behavior of img elements is to be inline, which means their positioning properties like left, top, right, and bottom are disregarded.

If you wish to position these elements, you can switch to a different display mode such as position: absolute that allows them to be positioned absolutely in relation to their offset container. In this scenario, the offset container would be #leftSide. You can achieve this with the following CSS rule:

#leftSide img {
    position: absolute;
}

For instance:

var numberOfFaces=5;
var theLeftSide=document.getElementById("leftSide");
var imgHeight=80;
var imgWidth=80;

function generateFaces(){

while(numberOfFaces>0){
var smileImg=document.createElement("img");

smileImg.src="http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
smileImg.style.height=imgHeight + "px";
smileImg.style.width=imgWidth + "px";
var randomTop=Math.random() * 400;
randomTop=Math.floor(randomTop);
console.log(randomTop);
var randomLeft=Math.random() * 500;
randomLeft=Math.floor(randomLeft);
console.log(randomLeft);
smileImg.style.top= randomTop + "px";
smileImg.style.left=randomLeft + "px";
leftSide.appendChild(smileImg);
numberOfFaces--;
}

}
body{
margin:50px;

}
p{
text-align:center;
font-size:18px;
}

#outer{
border:0.5px solid black;
position:realtive;
height:500px;
margin:20px;
}


#rightSide,#leftSide{
width:500px;
height:500px;
position:absolute;
}

#rightSide{
 left:700px;
 border-left:2px solid black;
}

#leftSide img {
    position: absolute;
}
<html>
<head>
<link rel="stylesheet" type="text/css" href="MatchingGame.css" media="screen" />
<title>Matching Game</title>
</head>
<body onload="generateFaces()">
<p>Click on the extra smiling face on the left side.</p>
<div id="outer">
<div id="leftSide"></div>
<div id="rightSide"></div>
</div>
<script type="text/javascript" src="MatchingGame.js" ></script>
</body>
</html>


It's important to note that I've repositioned the script tag at the end of the document, just before the closing </body> tag. Placing it at the top causes it to execute too early, before the elements referenced by getElementById are created. By moving it to the end, the element exists when the script runs, eliminating the issue where

var theLeftSide = document.getElementById("leftSide");
returns null.

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

a single button with dual functionalities

I am new to the development field and have a question about jQuery. I want a single button to perform two different actions. For example, let's say we have a button labeled Pause/Resume. When I click on the button, it should first display "Pause", and ...

Creating a nested function and utilizing the return statement in JavaScript

I am facing an issue with my custom function that contains an ajax call. I need to retrieve a variable from the ajax function within my custom function, but I'm unable to do so. Why is this happening? Possible solution 1: <script> function ...

Ensuring contact form accuracy using jQuery and PHP

Can't seem to figure out why I am always getting false from the PHP file even though my contact form validation with jQuery and PHP is working fine. Let me explain with my code: Here is the HTML: <form method='post'> <label& ...

Adding numerous JSON attributes to an anchor tag in thymeleaf

How can attributes provided in a single string from JSON be appended to an anchor tag in Thymeleaf? When the attributes are separate, they can be iterated through and assigned individually. However, in this scenario, all the attributes come from the same ...

Looking for an element that includes "== $0" right after the closing tag in HTML can be done using Xpath, CSS, or any other locators in Selenium with Python

a link to an image <div class=""><div>Mumbai, Maharashtra</div></div> Take a look at the above example for guidance. I attempted to use the code below but it failed to produce results: driver.find_element(By.XPATH,'//di ...

Aligning with the parent element and adjusting slightly towards the left side

.parent-div { box-sizing: border-box; min-width: 0px; padding: 1rem; min-height: 1px; margin: 0; border: solid 1px; } .child-div-one { box-sizing: border-box; margin: 0; min-width: 0px; min-height: 400px; display: flex; border: sol ...

Ways to soften the edges of a picture by utilizing CSS

I am trying to achieve a feathered effect on the edges of an image within an unordered list that contains 3 list items. Each list item has an image and 3 text-containing divs. I am looking for a CSS-only solution to achieve this effect. Currently, my webs ...

Full-Width Bootstrap Element

I am looking to design a pattern of alternating colored blocks that span 100% of the screen. An example of the "ideal" layout can be seen in the attached illustration, along with the current layout. Preferred design: Current layout: My initial approach ...

The event listener cannot be unbound

As a newcomer to javascript, I'm facing an issue that I couldn't find answers to despite searching extensively. Here is my problem: I have a module or class where I am attempting to create a draggable component on the screen. The objective is to ...

How to dynamically set Bootstrap navbar item as active based on current filename?

Currently, as I construct my website using the bootstrap framework, I am facing a minor challenge. I want to activate a menu item based on the filename by utilizing an if statement. For instance, when the filename is "about," the "about" tab should be act ...

JavaScript if else statement with 3 different scenarios

I'm having trouble figuring out why this code isn't working. It seems like there might be a conflict between the testRed and testGreen functions. If that's the case, could someone please suggest a better approach to solving this issue? Code: ...

Use Material UI TextField to prompt an email client or make a phone call

I am facing an issue with a MaterialUI TextField component. In certain situations, the TextField is disabled and I want it to be clickable as if it were an anchor tag leading to a phone number or email address. However, it seems that making the input behav ...

Dynamic Mesh modification and Raycasting in Three.js

When I clone a mesh from another mesh and then translate and rotate it, I encounter an issue with ray-casting. The point seems to be intersecting with the original position before translation and rotation. Here is a snippet of the code: const raycaster = ...

ability to reach the sub-element dictionaries in typescript

class ProvinciaComponent extends CatalogoGenerico implements OnInit, AfterViewInit { page: Page = new Page({sort: {field: 'description', dir: 'asc'}}); dataSource: ProvinciaDataSource; columns = ['codprovi ...

Maximizing performance through strategic database structuring with PouchDB/CouchDB

Recently, I've been researching efficient ways to store and retrieve data for my time management/project capturing application. I would greatly appreciate any insights on which storage strategy to utilize, or suggestions for alternative approaches, es ...

Achieve a top position in CSS layout without resorting to negative values

This may seem like a simple thing, but I'm struggling to achieve it without using negative values for padding-top. Here's how my site looks: Here is the CSS code I am using: .center { width: 1030px; margin: 0 auto; } .top-panel { backgr ...

Is it necessary to download and install plotly if I am using the cdn in my HTML file?

I'm currently developing an online application using Flask. The user input is collected with d3.js and sent to app.py, where it is used for an API call to retrieve the necessary data. This data is then returned in JSON format to JavaScript for renderi ...

Using jQuery, retrieve the "select" element within a specific row of a

I am working on a table row that has the following HTML structure: When the user interacts with the "Name" field, I trigger the "select" event and pass it to the nameDropChanged function. Once I have a reference to this select element, I need to change th ...

XSLT transformation eliminates HTML elements from mixed content

Can XSLT maintain anchors and other embedded HTML tags within XML? Situation: I'm currently attempting to transform an HTML document into XML using an XSL stylesheet with XSLT. The original HTML content contained anchor tags scattered throughout (e.g ...

Utilizing a checkbox within a select dropdown component in Vue

Has anyone come across a checkbox dropdown feature in Vue? I have been searching online but couldn't find any examples or resources related to this. If someone has a working skeleton for it, please share! ...