Add a <div> element to a webpage in a random location every time the page is refreshed

I have a variety of 2 types of <div>s displayed on a single page.

Collection 1 consists of:

<div class="feature">content 1</div>
<div class="feature">content 2</div>
...and so forth.

Collection 2 consists of:

<div class="native-content-1">My native code 1</div>
<div class="native-content-2">My native code 2</div>

Whenever the page loads, a <div> should be randomly selected from collection 1 and added to a randomly chosen <div> from collection 2.

Answer №1

Utilizing a random function that generates a number within a specified range.

Here is the expected outcome:

$(document).ready(function() {
  function onPageLoad() {

    var no_of_features = $(".feature").length
    var selectedRandomFeature = getRandomInt(0, no_of_features - 1);


    var no_of_natives = $("[class^='native-content-']").length;
    var selectedRandomnative = getRandomInt(1, no_of_natives)
    $($(".feature")[selectedRandomFeature]).append($(".native-content-" +   selectedRandomnative))



  }

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

  onPageLoad();
});
.feature {
  height: 100px;
  width: 100px;
  background-color: black;
  color: white;
  float: left;
  margin-left: 10px;
  margin-top: 20px;
}
[class^='native-content-'] {
  height: 50px;
  width: 50px;
  background-color: green;
  color: white;
  margin-top: 10px;
  margin-left: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="native-content-1">My native code 1</div>
<div class="native-content-2">My native code 2</div>
<div class="native-content-3">My native code 3</div>
<div class="feature">content 1</div>
<div class="feature">content 2</div>
<div class="feature">content 3</div>
<div class="feature">content 4</div>
<div class="feature">content 5</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

Aligning Description Item components horizontally in antdLearn how to easily horizontally align Description

Currently, I am utilizing the `antd` Description components. In this scenario, when there is no `title` for the items, the value should be aligned to the left. You can see an example of this alignment in the image below: https://i.sstatic.net/Ah70f.png I ...

Utilizing HTML and CSS allows for creating a responsive layout with three elements such as this

Need help with CSS to align three elements in a row, where the first two are on the left and the third is on the right. The layout should adjust so that when the window size is smaller, the second element moves below the first while the third element stays ...

PhoneGap Troubleshooting: Device Plugin Malfunctioning

I'm having trouble getting the device plugin to work with my Cordova/PhoneGap project. Currently, I am using Cordova version 3.3.1-0.1.2. I followed the documentation and installed the plugin using the following command: C:\ProjectFolder>pl ...

Issues with premature execution of Angular JS code have been observed at times

Currently facing an issue with my code where the updateProduct() function call is happening before the forEach loop begins running on about 1 out of every 10 page loads. Not sure why this is occurring or how to solve it. Any insights on what might be causi ...

Display loading spinners for multiple ajax requests

At the moment, I am displaying spinners using the ajax setup method call: (function() { $.ajaxSetup({ beforeSend: showLoader, complete: hideLoader, error: hideLoader }); })(); While this setup is functioning properly, the ...

"Implementing a dynamic way to assign values to different item types in React

There is an object with multiple values inside: const [sort, setSort] = useState({ "city": [], "price": [], "year": [] }); When the "add" button is clicked, the "city" value should be updated to include certain va ...

Using Angular 4 for HTML 5 Drag and Drop functionality

I have been working on integrating native HTML 5 drag & drop functionality into my angular application. While I have successfully implemented the drag and dragOver events, I am facing an issue with the drop event not firing as expected. Here is the snipp ...

Inject $scope into ng-click to access its properties and methods efficiently

While I know this question has been asked before, my situation is a bit unique. <div ng-repeat="hello in hello track by $index"> <div ng-click="data($index)"> {{data}} </div> </div> $scope.data = function($index) { $scope.sweet ...

Can you modify a single attribute for multiple child elements under a parent tag in Visual Studio Code simultaneously?

Imagine a scenario where you are faced with 30-40 options and need to update the name attribute from blank to something more appropriate. Is there a method in visual studio code that allows you to do this in one go? It would be a fantastic feature to have. ...

Alternative solution to fix navigation issue in Flex 4.5 when navigatetoURL is not functioning as intended

Perhaps you are aware of the compatibility issues that Google Chrome and Safari have when using navigatetoURL, as it only works in Internet Explorer. To address this problem, I found a code snippet on a forum which consists of a JavaScript function embedde ...

Combining MarkDown elements into a DIV or a custom HTML tag

I have utilized the Jeykll tool to convert mark down content into HTML. I am looking to group the following mark down elements within a div element or another custom HTML tag. Markdown #Multiple Axis {:.title} Different types of data can be vis ...

Strange Behavior of Zoom DIV Effect during Rapid Hovering

Here is the code I am working with: http://jsfiddle.net/8fvJN/15/ Whenever I try to quickly hover from one box to the next, a strange effect occurs where they start behaving erratically. If you hover between boxes rapidly, you will observe this behavior. ...

Is it possible to store data in a nested object using MongoDB?

I'm having trouble inserting the data from req.body into my mongodb collection. In this route, when the add method is triggered, I am attempting to create a query that will store the data from req.body in a nested collection array. router.post(&apos ...

Exploring the concept of promises in node.js for recursive functions

I'm attempting to use recursive calls in order to fetch data from redis, halting and returning when the members return null. My data is inserted as shown below: SADD parents.<name> <parent1> <parent2> SADD parents.<parent1> & ...

Prevent user input in Vue.js until the value has been modified

Need help handling initial input values: <input type="text" v-model="name" ref="input" /> <button type="submit" :disabled="$refs.input.defaultValue == $refs.input.value">Submit</button> Encountering an error with the disabled binding: C ...

Error in ReactJS: TypeError - Trying to convert undefined or null as an object

Here is the affected code with Typescript errors in local. The component name is correct: {template.elements.map((element: TemplateElementModel, i) => { const stand = roomStands?.find( (stand: ExhibitorModel) => stand.standN ...

An event change leads to the activation of another event

I've set up some input fields and linked their values to a JavaScript variable. Strangely, the drinkInput value always shows up as blank for some reason. When the typeInput event is triggered, its value prints correctly in the console followed by an e ...

How Jquery's Ajax can terminate SQL processes in PHP

Currently, I have a script that reads a .CSV file line by line and inserts the data into a database using an "INSERT QUERY". I am looking for a way to allow the user to stop this script at any given time. Below is my AJAX call: postselect = $.post(&apos ...

Flask and the steps to modify CORS header

While working on my localhost, I came across a CORS error when building an application to handle search queries for a different domain. The specific error was: "Cross Origin Request Blocked... (Reason: CORS header 'Access-Control-Allow-Origin' mi ...

Issue encountered when attempting to include jquery.min.js due to a jquery conflict

I've been experimenting with the jquery.scrollableFixedHeaderTable.js extension in order to create a table header that remains fixed as you scroll through the table. However, when I attempt to incorporate jquery.min.js for a tooltip plugin, the scrol ...