Various results can be produced based on the .load() and .resize() or .scroll() functions despite using the same calculation methods

I'm currently working on developing my own custom lightbox script, but I've hit a roadblock.

For centering the wrapper div, I've utilized position: absolute and specified top / left positions by performing calculations...

top:

_center_vertical = function() {
  return (($(window).height() - wrapper.height()) / 2) - (options.margin + options.border) + $(window).scrollTop()
}

left:

_center_horizontal = function() {
  return (($(window).width() - wrapper.width()) / 2) - (options.margin + options.border) + $(window).scrollLeft()
}

The wrapper div is centered upon .load() as well as when $(window).resize() / $(window).scroll() events occur.

However, after loading and appending the image to wrapper, while horizontal centering is accurate, vertical centering is slightly off by around 10px or more.

Whenever the browser window is resized or scrolled, the function is called which animates the centering process using the same functions for calculating top and left. During these events, the image is centered correctly.

I attempted to utilize jQuery deferred.then() in order to compute the top / left post-appending the image, but unfortunately, it didn't yield any changes in the outcome.

Example: http://jsfiddle.net/vfMNQ/


Initially, I presumed that the discrepancy in the top position was due to modifications like wrapper padding (i.e., border), yet this assumption turned out to be incorrect.

To investigate further, I inserted

console.log('image load height: ' + ((($(window).height() - wrapper.height()) / 2) - (options.margin + options.border)) + 'px')
within .load() and .scroll(), revealing an unexpected 21px difference regardless of settings. With the default values being a 10px border and 30px margin, the origin of this additional 21 pixels remained elusive.

While reluctantly considering adding + 21 as a workaround, the mystery surrounding the issue remains unsolved by anyone so far.

Answer №1

It seems like the issue lies within the loading div:


    .lbe-loading  {
    background: #578DB2 url(/public/images/loading.gif) no-repeat center center;
    width: 32px;
    height: 32px;
    padding: 5px;
    }
    

When calculating height: 32 + padding: (5 * 2) = 42

42 / 2 = 21px

It seems that the image is being added with the loading div still attached to the wrapper.

wrapper.append(loading);

...

$(function() {

var img = $(new Image());
img.load(function() {
wrapper.append(this)    // .lbe-loading still appended here 
.css({                  // Position wrapper. 
    ...
});

loading.remove();       // This removes it too late. 

If the .append(loading) is removed, the centering works correctly.

To avoid this issue, place .lbe-loading on a different div so it doesn't affect the wrapper's height.

Answer №2

Possible solution:

Make sure to allow the image to load fully before trying to calculate the height of the wrapper element.

For example, instead of immediately calculating the height after using append(this), wait for the browser to display and load the image properly.

During debugging, it was observed that wrapper.height() increased by 40 pixels after the display was resized. This change in height corresponds to the border and margin properties. Adjusting these properties also resulted in changes to the calculated difference.

Answer №3

There seems to be a delay in the wrapper obtaining the height and width of the image. The jQuery script for centering is running before the browser has completed its reflow process and provided 'wrapper' with the necessary dimensions of the image.

I took your fiddle, made some adjustments, and resolved the issue. You can see the updated version here: http://jsfiddle.net/3th5k/. I set the height and width of the wrapper using JavaScript before executing the centering code. This ensures that the calculation uses accurate data from the JavaScript image object rather than relying on the DOM.

Additionally, I replaced the css statement 'opacity: 0' with .hide(). This change was made because opacity can cause compatibility issues with Internet Explorer, potentially leading to problems later on.

Cheers!

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 Sortable feature is functional in all browsers except for Firefox

I am currently utilizing the following example () within my asp.net application. I have successfully implemented the sortable feature in all browsers except for Firefox, where it seems to trigger the event but doesn't execute the code. $('.c ...

Looking to distinguish selected options in a multiple select in AngularJS by making them bold?

When working with Angular, I have a multiple select drop down with options such as Select fruits, Apple, Orange, Banana. How can I make the selected options, like Banana and Apple, appear in bold and change background colors? ...

Troubleshoot: Laravel controller not receiving inputs

I'm currently facing an issue with passing a creation form to a controller. I have set up the route and the ajax call, which is communicating with the route successfully. However, I am encountering a problem where the form values are not being display ...

Using jQuery AJAX enforces the use of HTTPS

Here is the current setup: Using jquery version 2.1.1 Employing nodejs (not a crucial factor) Making requests over https The issue at hand: When using $.getJSON() and $.get(), the URL requested appears as "". Despite confirming the correctness of the UR ...

Listening for key combinations in VueJS using a mounted event listener

I am facing an issue with my global key listener - it only catches single key strokes. How can I modify it to capture combinations like ctrl+enter? mounted() { window.addEventListener ( "keypress", e => { console.log ...

What could be causing the slow compilation of my Next.js pages within the app directory, and what steps can be taken to improve the speed of this

Currently, I am working on a Next.js project that uses the 'app' directory structure. However, during local development, I have been facing significant delays in compile times. Here's a breakdown of the compile times I am encountering: - Th ...

Creating a sequence of HTTP calls that call upon themselves using RxJs operators

When retrieving data by passing pageIndex (1) and pageSize (500) for each HTTP call, I use the following method: this.demoService.geList(1, 500).subscribe(data => { this.data = data.items; }); If the response contains a property called isMore with ...

Comparing the differences between while loops and setTimeout function in JavaScript

I'm currently deciding between using a while loop or a setTimeout function in JavaScript. As I understand it, due to JavaScript's single-threaded nature, having one function run for an extended period can hinder the execution of other functions s ...

My divs are multiplying twice as fast with every iteration of the Javascript For Loop

Recently, I developed a script that generates a series of fields based on a number provided by the user (k). Initially, I had a script that would create the correct number of fields. However, I decided to arrange them like vectors on the screen, so I made ...

The Distinction between Object.assign and the simple assignment operation

Could you please explain the distinction between these two lines of code? Object.assign(otherObject, { someNewProperty: '' }); vs. otherObject.someNewProperty = ''; Also, which one of these methods is more efficient in terms of sp ...

What is the best way to loop through a list of questions and save the answers in an array of user input?

I'm encountering a challenge with iterating through an array of questions to correctly display them on the document. The initial code snippet provided below demonstrates what I aim to accomplish without using prompts. Currently, I have set up an arr ...

Aligning validation schema with file type for synchronization

Below is the code snippet in question: type FormValues = { files: File[]; notify: string[]; }; const validationSchema = yup.object({ files: yup .array<File[]>() .of( yup .mixed<File>() .required() .t ...

Connecting Angularfire2 with Firestore for advanced querying

Glad you stopped by! Currently, I have two Firestore Collections set up in my Angularfire2 application. One consists of "Clients", while the other contains "Jobs". Each client can have multiple jobs assigned to them, and vice versa. I've been workin ...

How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows: name | date | agencyID test 2016-03-17 91282774 test 2016-03-18 27496321 My goal is to have a dropdown menu containing all the &apo ...

Having trouble locating node_modules/nan on your system?

Trying to globally install this project is proving to be a challenge as I run the command npm i -g. Followed these steps: git clone https://github.com/superflycss/cli cd cli npm i npm i -g However, encountered this result: ole@mki:~/cli$ npm i -g npm W ...

What is preventing my webpage from responding to mouse clicks?

Take a look at my example posted below: http://jsfiddle.net/abt5w/1/ This is the HTML code snippet: <p class='para'> <div class='test'>Hello</div> </p> And here's the JavaScript code: $('.test&apo ...

Breaking Down the Process of Exporting a Next.js Static Website into Manageable Parts

I am facing memory issues while building my website using Next.js's Static HTML Export. The site has a large number of static pages, approximately 10 million. Is it feasible to export these pages in batches, like exporting 100k pages in each build ite ...

Controlling the document object model of a third-party website within the Electron framework

I am completely new to electron. My main goal is to load a URL and then execute some Javascript that will make changes to the DOM. Currently, my approach involves creating a BrowserWindow that loads the URL, and I understand that I can utilize webContents ...

Mapping a list with sections can easily be achieved by breaking down the elements

I'm facing an issue with listing array data under sections using .map in React. I know how to use .map to list the entire array, but struggling to list each item under its respective section. Currently, I have to use .map separately for each section. ...

Make sure to use the jQuery load function to specifically target and retrieve

Hello, I'm new to working with jQuery and I have a question about adding a vertical scrollbar to a jQuery modal window. Specifically, I want the scrollbar to appear when there is a large amount of text within the modal window. Can you guide me on wher ...