Randomly positioning an image while the page is loading

I've been developing a portfolio website to showcase my design work, but I've encountered a minor issue.

My goal is to have the images load in random positions and then make them draggable using Dragabilly.

However, sometimes all the images end up clustered in the top corner without their positions being properly defined. Despite this, dragging functionality still works. I suspect that this could be due to the images not fully loading before running the script, but I'm uncertain.

You can view my live site here

Here's the code snippet I'm currently using...

$ ->
$('#menu-button').on 'click', ->
    $('#menu').toggleClass 'closed'
    return

if $(window).width() > 960
    $img = $ '.work-imgs img'

    wdoh = $('.work-desc').outerHeight()
    wl = ($(window).width() - 384) / $img.length
    wh = $(window).height() - wdoh

    $.each _.shuffle($img), (i, e) ->
        e.onload = ->
            rm = wh - $(e).height()
            $(e).css
                'left': i * wl + (Math.random() - .75) * 96
                'top': wdoh + Math.random() * rm
            return
        return

    $d = $img.draggabilly()
    $d.on 'pointerDown', ->
        $d.css 'z-index', 0
        $(this).css 'z-index', 1
        return

return

Example image

Answer №1

The issue at hand is that the browser caches images, which can be beneficial but may prevent the onload event from triggering for all images. In order to ensure the callback is assigned correctly, you must verify if the image has already been loaded.

In order to determine if the image has been loaded prior to the execution of JS code, you can utilize the complete property (mdn).

$.each _.shuffle($img), (i, e) ->
  callback = ->
    rm = wh - $(e).height()
    $(e).css
        'left': i * wl + (Math.random() - .75) * 96
        'top': wdoh + Math.random() * rm

  # if the image isn't cached, the onload will fire
  e.onload = callback
  # if the image is cached in the browser, and therefore already
  # loaded, you can run your callback immediately
  callback() if e.completed

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

The type 'RefObject<HTMLDivElement>' cannot be matched with type 'RefObject<HTMLInputElement>' in this context

Encountered an error message: Issue with assigning types: Type '{ placeholder: string | undefined; autoComplete: string | undefined; "data-testid": string | undefined; onChange?: ChangeEventHandler<HTMLInputElement | HTMLTextAreaElement&g ...

The positioning of the Kendo UI window is off-center

I have encountered a problem with the alignment of the Kendo Window. There is a simple fiddle available to demonstrate this issue. Despite having ample space for the Kendo window to show without triggering the browser's vertical scroll bar, the cente ...

Enhance D3 Version 6 Stacked Bar Chart with Spacing and Interactive Features

My bar chart lacks the spacing between bars that I intended to achieve, and the interactive tooltip doesn't show up when hovering over the bars. I could use some assistance with this. The purpose is to display the value of a specific color when hoveri ...

Exploring the Various Textures within the CANVAS 2D Context

Exploring new techniques for filling the canvas, I am currently trying to add texture to an object similar to the blobs from the blob example (http://www.blobsallad.se/). The challenge is that the current example is utilizing the 2D context without webGL i ...

Utilizing server-side variables with JavaScript in Node.js, Express.js, and EJS

Hello everyone, I am just getting started with backend programming and I'm currently working on a project where I need to send an array of objects to the client. My goal is for the client to then add an object to this array. I am using node.js in conj ...

No form data available during IE10's unload event

My method of saving form data in emergencies by hooking window.unload and sending it via ajax using POST works well in browsers like IE9 and Chrome. However, I have noticed that in IE10, the form data is empty when sent through POST (using GET as a worka ...

Guide to sending a POST request from within my application

I'm facing an issue with using $resource for making a post request in my app. Here is the code snippet from my Angular module: angular.module('myApp').factory('Product', ['$resource', function ($resource) { ...

Exploring the power of Angular's ng-repeat to generate hierarchical lists

I am looking to display a structured list of layers and sublayers by looping through an object using ng-repeat. var lyrslist = [ { layername: "Base Maps", layertype: "layer" }, { layername: "Open Street Map", layertype: "sublayer" },    { layer ...

Tips for correctly center aligning a Div element

I'm facing some challenges with properly centering my website It appears to be centered when I zoom out. However, for users who don't zoom out, it looks misplaced. Do you have any suggestions? The site was built using all AP divs and even with a ...

Finding a solution to this issue in Angular will consistently result in a false outcome

Can anyone explain why I keep getting the error message "This condition will always return 'false' since the types 'typeof ChartType' and 'ChartType' have no overlap" whenever I try to compare charTypeEnum with ChartType.text? ...

What is the correct way to implement the chain populate method in a Node.js application?

I am developing a blog application with node.js and react, utilizing MongoDB and Mongoose's .populate method to fetch data across collections. Currently, I have three collections: Post, User, and Category. Successfully, I managed to link the username ...

The Server-Side Rendered page is experiencing inconsistencies in rendering

I am currently working on a straightforward NextJS project with just one page. The application is configured to utilize redux, next-redux-wrapper, and redux thunk. It is important that the page always undergo server-side rendering. Here is an example of h ...

The "events" module could not be resolved in React-Native

The server encountered an internal error: 500 URL: Body: {"message":"There was an issue resolving the module events from the specified directory. This may be due to a module not existing in the module map or directories listed.","name":"UnableToResolveEr ...

Upon loading, the Carousel is visible instead of being hidden, which is contrary to its intended behavior

Any help would be greatly appreciated as I am struggling with creating a web page featuring tabs for "London, New York, Shanghai". The initial page displayed is the "welcome" page with the other tabs hidden on load. I successfully implemented a carousel f ...

How can we delay UI updates until API calls have finished processing a chunk of requests in Redux-Saga without affecting the responsiveness of the user interface?

function* fetchDataFromChunks(dataList = []) { const segmentedData = yield call(splitDataIntoChunks, dataList, 5); for (let chunk of segmentedData) { const requests = chunk.map(item => call(retrieveImageData, item._id, item.im ...

What is the most effective method for implementing a background repeated image in Foundation 4 framework?

Currently, I am utilizing the foundation4 framework for my website. In order to achieve a repeating tiled background, I have crafted a custom CSS file and included the following code snippet: body { background: url(img/floorboardsbg.jpg) repeat; } Whi ...

Issue with transforming rotation in Quirks mode

Currently, I'm developing a website in quirks mode which does not allow the use of . In my project, I am facing an issue where CSS3 translate image is not working in IE10 and 11, although it works fine in IE9 due to the limitations mentioned above. Is ...

The div element displays a vertical scrollbar exclusively

Can you explain why the div is only displaying a vertical scrollbar? Although the canvas is larger than the div in both dimensions: div { padding-top: 2px; height: 709px; width: 889px; overflow: auto; } <div> <canvas width="1405" sty ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

Ways to retrieve JSON data through multiple levels of nested if statements

Currently, I am using CodeIgniter to work on a small project involving creating batch lists. When an admin attempts to create a new batch list, they must input the start date, end date, start time, and end time. The system will then check the database to s ...