Upon clicking, randomly display words in a container on your mobile device at various positions

After posting a question on Stack Overflow yesterday, I was advised to create a new one in order to receive a more specific answer.

The code I have currently displays words on the page when a button is clicked.

Everything works perfectly, but I am wondering if it is possible to contain the word display within a designated container?

I would like the words to only be displayed on mobile devices, as on desktop there is a lot of scrolling required to see all the words. I attempted to place the display in a 300x300px box, but the words are still appearing everywhere. Is it achievable using Bootstrap grid, media queries, or another type of container? Or maybe I need to apply a different Javascript rule?

Thank you for your assistance!

var words = [
  'Hello',
  'No',
  'Hi',
  'Banana',
  'Apple'
];
var visible = 0;

document.querySelector("form").addEventListener("submit", function(e) {
  e.preventDefault();

  var fullWidth = window.innerWidth;
  var fullHeight = window.innerHeight;

  var elem = document.createElement("div");
  elem.textContent = words[visible];
  elem.style.position = "absolute";
  elem.style.left = Math.round(Math.random() * fullWidth) + "px";
  elem.style.top = Math.round(Math.random() * fullHeight) + "px";
  document.body.appendChild(elem);

  visible++;
});
<form>
  <input type="submit">
</form>

Answer №1

Your code has been slightly modified to ensure it functions properly.

var words = ['Hello','No','Hi','Banana','Apple'];
var visible = 0;
var container = document.getElementById("container");
var containerWidth = container.offsetWidth;
var containerHeight = container.offsetHeight;

document.querySelector("form").addEventListener("submit", function(e) {
  e.preventDefault();

  var elem = document.createElement("div");
  
  elem.className = "elem";
  elem.textContent = words[visible];
  
  document.body.appendChild(elem);

  var left = Math.round(Math.random() * containerWidth); 
  var maxRight = containerWidth - (left + elem.offsetWidth + 5);
  
  if (maxRight < 0) {
    left -= Math.abs(maxRight);
  }

  var top = Math.round(Math.random() * containerHeight); 
  var maxBottom = containerHeight - (top + elem.offsetHeight + 5);
  
  if (maxBottom < 0) {
    top -= Math.abs(maxBottom);
  }

  elem.style.left = left + "px";
  elem.style.top = top + "px";
  
  container.appendChild(elem);

  visible++;
  
});
#container {
  border: 1px solid black;
  height: 500px;
  width: 500px;
  position: relative;
}

.elem {
  display: inline-block;
  position: absolute;
}
<form>
  <input type="submit">
</form>

<div id="container"></div>

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

Position a broader div within a slimmer one

<div id="narrow"> <div id="wide"> </div> </div> In my web layout, there is a div with the ID of "narrow" containing another div with the ID of "wide", which has a wider width than its parent. The div with the ID "narrow" can ...

Save the Selenium HTML source code into an HTMLDocument element

Is there a way to save the HTML code fetched using Selenium (via Excel VBA) into an HTMLDocument element? The following example demonstrates utilizing Microsoft Internet Controls and Microsoft HTML Object Library for automating Internet Explorer. Dim IE ...

Troubleshooting Codeigniter CJAX Installation: Handling Errors

I am currently attempting to integrate CJAX with Codeigniter, but I'm encountering some difficulties with the official documentation. Despite my best efforts, I've been unable to successfully implement it. After downloading CJAX and extracting i ...

Angular controller makes several $http requests to a cross-origin REST API

I'm currently attempting to make multiple GET requests to my own REST API built in Java using Spring. Out of every 10 times, both requests are handled successfully 3 times and 7 times one of the HTTP requests fails with a 'No Access-Control-Allow ...

Is there a way to address this scrollbar issue without relying on HTML?

Currently, I am working on a website where the only customization allowed is related to CSS. While I've been able to make progress, I've encountered an issue with the scrollbar placement. The scrollbar is extending beyond the boundaries of the di ...

What is the reason for browsers changing single quotation marks to double when making an AJAX request?

Jquery: var content = "<!DOCTYPE html><html lang='en'><head><meta charset='utf-8'><meta http-equiv='X-UA-Compatible' content='IE=edge'><meta name='viewport' content='w ...

What is the best way to set up a website subdirectory and connect a button to it?

A group of friends and I recently created a real-life version of Among Us, but we think it could be even better if we had a website to go along with it. After doing some research and learning about HTML, CSS, JavaScript code, as well as websockets, I manag ...

Using VueJS transitions may require the use of setTimeout for them to work

My code successfully slides out a menu: Vue.set(this.filterStyles, filterIndex, { display: "block", height: "auto", }); let filterValuesElHeight; Vue.nextTick().then(() => { let filterValuesEl = document ...

Adjust the heights of certain headers in an HTML table, not all of them

Here is the link to my JSBin: https://jsbin.com/xofaco/edit?html,css,output I am facing an issue with an HTML table that has both nested headers and regular headers. My goal is to make all headers equal in height, specifically I want columns labeled "four ...

Utilizing routing in Sencha for seamless back button functionality

I'm new to using Sencha and I need help with implementing support for the back button in Android using Sencha Touch2 Routing. I read through the Sencha documentation, which mentioned scenarios like "#products/123". However, in my case, only the views ...

Tips on how to target the center of a slider thumb with a pointer using CSS and jQuery

One of the features I have implemented is to display the price range and the most repeated price (Mode). In order to illustrate this, I used the range input type but deactivated it so that users cannot move it. Below you will find my HTML, CSS, and JS cod ...

Flexible design for your website content wrapper

When I display the content on my website, it sometimes overlaps the footer because the wrapper does not adjust its size based on the content. I set the height to an absolute value and now I need to find a more flexible option to prevent this issue. I' ...

There are a total of 152 issues found in the index.tsx file within the react

Despite everything working correctly, I am continuously encountering these errors. Is this a common occurrence? What steps can I take to resolve them? I have developed my react application using Javascript instead of Typescript; however, I don't belie ...

Customizing table header sort icons in PrimeNG 15.4+: A step-by-step guide

The most recent update in PrimeNG brought about a change in the way sort icons are implemented. Previously, they used an i tag with CSS classes which could be customized easily using my company's icons: https://i.sstatic.net/f0Nrq.png However, the n ...

What is the best way to combine JavaScript arrays and sort them by their respective positions?

Is it possible to merge arrays in javascript based on their index/position order? I've been trying to achieve this but haven't come across any examples. var array1 = [1,2,3,4] var array2 = [a,b,c,d] var array3 = [!,@,#,$] var mergedArray = [1,a ...

Leveraging lodash to handle JSON with multiple matches in Javascript

Imagine having an array structured like this: var users = [{ users : [{ user :'harry' }, { user : 'potter' }, { user : 'jinny' }, { user : 'weasly' }], age : 3 ...

"Hovering over the navigation tab does not trigger the dropdown menu

Can't seem to get my dropdown menu on the right to work when hovered. I feel like I must be missing something really simple, but I can't figure it out! When I use .vanish:hover .dropdown, it's not quite hitting the mark. What am I doing wron ...

Exploring the concept of union types and typeguards in TypeScript

I'm struggling with this code snippet: function test(): any[] | string { return [1,2] } let obj: any[] = test(); When I try to run it in vscode, I get the following error message: [ts] Type 'string | any[]' is not assignable to type & ...

Customizing the style of a dropdown menu in React Material UI using NativeSelect

In our previous projects, we have utilized the NativeSelect components. Now, the task at hand involves altering the appearance of the dropdown Menu within the NativeSelect. If we were to switch to using Select instead, employing the MenuProps property wo ...

Transforming DayOfYear data in Javascript to utilize with Flot

Attempting to utilize the flot jQuery library for a display, but running into an issue with the X Axis showing dates. The data being received is in DayOfYear format instead: var data = [[192,6.9],[191,49.52],[190,2],[189,0], etc...] Numbers like 192, 19 ...