Creating divs with randomized positions using JS and jQuery

I encountered a problem with my code when running it on certain viewport sizes. It seems to freeze, requiring me to close the tab.

I attempted to implement a backup script that would terminate the loop if it froze, but it hasn't been effective.

Could someone identify what's causing the freeze or point out any errors in the script?

The code is being executed on this site:

You can find the JS code here:

var pos = function(){
var containerW = $("article").width();
var containerH = $("article").height();
var langH = parseInt($( ".languages" ).position().top + $( ".languages" ).height());
var langW = parseInt($( ".languages" ).position().left + $( ".languages" ).width());
var creditW = parseInt($( ".credit" ).position().left - $(".link:first").width() + 15);
var positions = [];
var froze = false;
setTimeout(function(){froze=true;}, 2000)
$('.link').each(function() {
    var coords = {
        w: $(this).outerWidth(true)+5,
        h: $(this).outerHeight(true)+5
    };
    var success = false;
    while (!success)
    {
        coords.x = parseInt(Math.random() * (containerW-coords.w));
        coords.y = parseInt(Math.random() * (containerH-coords.h));
        var success = true;
        $.each(positions, function(){
            if (froze){return false;}
            if (
                (coords.x <= langW &&
                coords.y <= langH) ||
                (coords.x >= creditW &&
                coords.y <= langH) ||
                (coords.x <= (this.x + this.w) &&
                (coords.x + coords.w) >= this.x &&
                coords.y <= (this.y + this.h) &&
                (coords.y + coords.h) >= this.y)
            )
            {
                success = false;
            }
        });
    }
    positions.push(coords);
    $(this).css({
        top: coords.y + 'px',
        left: coords.x + 'px',
        display: 'block'
    });
})};

var waitForFinalEvent = (function () {
  var timers = {};
  return function (callback, ms, uniqueId) {
    if (!uniqueId) {
      uniqueId = "Don't call this twice without a uniqueId";
    }
    if (timers[uniqueId]) {
      clearTimeout (timers[uniqueId]);
    }
    timers[uniqueId] = setTimeout(callback, ms);
  };
})();

$(document).ready(
    pos()
);
$(window).resize(function () {
    waitForFinalEvent(function(){pos();}, 500, "resize");
});

Answer №1

You're facing a couple of challenges here. It seems like the size of your A.link elements is only determined by the viewport's height, making it difficult to fit all the links if the viewport is tall and narrow.

Another issue is that when the links can't be placed, your code continuously tries without stopping. Instead of using a perpetual loop with while (!success), it would be more efficient to limit the number of attempts:

var success = false;
for (var attempt = 0; !success && attempt < 50; attempt++)
{
     ....
}

This approach prevents your script from getting stuck and allows for better control. You could also consider introducing a tolerance level as the number of attempts increases, allowing for some overlap between the links.

Answer №2

The reason your while loop is running indefinitely is because you have unintentionally created two instances of the variable success. By redefining success within the loop using var success = true, you are essentially creating a new variable that is separate from the original one. To fix this issue, simply remove the var keyword from var success = true.

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

Error Message for Sequelize Validation Fails to Appear as Expected

I am trying to implement Sequelize model validation in order to validate a form field. When the book or author fields are left empty, I want this message to be displayed: Oops! An error occurred. "Title" is required. "Author" is required. The issue I&ap ...

The incorrect value of variable V is being passed to the doSomethingWithData(v) function. This could lead to unexpected results

const Greetings = () => { const [num, setNum] = React.useState(1); React.useEffect(() => { setTimeout(async () => { await setNum(2); processData(num) }, 3000) }, []); retur ...

Utilizing Flask to gather information from a leaflet map

I am currently working on creating a webpage using Flask. The webpage features a leaflet map where users can click to create a marker that opens a popup window with a link. The link's purpose is to open a new page displaying the longitude and latitude ...

The CSS file I've linked to in my HTML (ejs) document seems to be getting

As I work on developing my app from the backend, I am encountering an issue with loading CSS locally on my page. I am utilizing Node.js, Express.js, and EJS for my pages - part of the MEN/MEAN stack. <link href="../public/stylesheets/style.css" rel="st ...

Ways to automatically close the dropdown button when the user clicks outside of it

Is there a way to automatically close the dropdown button when a user clicks outside of it? Check out this link for possible solutions ...

Ways to eliminate an empty space within an element

I am experiencing an issue where the text in my h2 tag is not aligned with the left of the element, as shown in the picture. Is there a way to eliminate this blank space or make the text stick to the left? Below are the CSS attributes being used: h2 { ...

FireFox is showing inconsistencies in response to the jQuery GET request, while Chrome is responding correctly

$.ajax({ url: 'https://api.imgur.com/3/album/' + sharedAlbumID, type: 'GET', beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Client-ID '+imgurClientID);}, success: function(resp) { ...

"Enhance Your CSS Styling with an Additional Dot for Dotted Under

Is it possible to make the dots at the end and sometimes beginning of a word thicker and more round? https://i.stack.imgur.com/W9WPi.png ' CODE <span style="border-bottom: 3px dotted #111;">Personal Project Magazine Ads Personal Project Magaz ...

Having trouble transforming JSON into an array using Angular.js

Hello there, I'm currently facing some issues with Angular. I've made a request using $http and received a JSON response like: {"y":"1","a":"0"} I need to convert it into an array format like: {y: 1, a: 0} I've tried using angular.fromJs ...

Typescript is throwing a Mongoose error stating that the Schema has not been registered for the model

I've dedicated a lot of time to researching online, but I can't seem to figure out what's missing in this case. Any help would be greatly appreciated! Permission.ts (This is the Permission model file. It has references with the Module model ...

Scroll to Reveal Content Hidden Behind Hero Image

I am absolutely enamored with the Beautiful Stories section on Medium's website. The way they showcase their content is just mesmerizing. One thing I've noticed is how the cover image and preview of the content changes as you resize your browser ...

jQuery method for implementing alternating row colors that are not sequential

Starting from scratch here. I've fetched a table from a remote server where odd rows are white and even rows are grey. Some rows have been hidden: $("td").filter(function(){ return $(this).text()=='R1';}).text('Row1'); //white $(" ...

Rotating images on a canvas

We're currently implementing Ionic and Angular in our project. One issue we are facing is regarding image rotation on canvas. When we click on an image, the rotation works perfectly if it's a jpg file. However, when we pass a base64 image, the r ...

Submit a form utilizing jQuery's ajax function

I am currently facing an issue with my use of the $.ajax post method. My intention is to submit form data on the current page itself, but somehow the script is redirecting to the action page. If anyone could pinpoint what's causing this redirection ...

How to retrieve TypeScript object within a Bootstrap modal in Angular

Unable to make my modal access a JavaScript object in the controller to dynamically populate fields. Progress Made: Created a component displaying a list of "person" objects. Implemented a functionality to open a modal upon clicking a row in the list. ...

What is the best way to incorporate flags in a nodejs application when using npm run-script?

I have a NodeJS file that I execute using an "npm" command. I've been attempting to display all arguments (including flags). When the file is executed by directly calling the node executable, it functions correctly. However, when I use the npm command ...

There was a problem finding the correct address indicated by the marker

I am working on an Android app using PhoneGap, and I need to display a marker on a Google map at a specific latitude and longitude. When the marker is clicked, I want to show an info window displaying the address associated with that location. However, t ...

Execute a Flask function at regular intervals

Within my HTML document, there is a span element that displays the result of the getStatus() function: <span id="sysStatus" style="font-weight: bold;">{{ status }}</span> The logic behind the getStatus() function is as follows: def getStatus ...

The Ant Design form is not updating values after using setFieldsValue in Testing Library

Currently, I am working with the testing-library/react-hooks library and using renderHook. One issue I'm facing is that I am unable to set a value for my antd form using setFieldsValue. It seems like the value is not being set properly. What could be ...

Error detected in JSON syntax... Where is it hiding?

After running the code through jsonlint, it flagged an error on line 17. However, upon close inspection of the file which contains about 1000 lines, I couldn't pinpoint the issue. It's possible that the problem lies further down the file, but I w ...