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

What methods can be used to modify the behavior of tiptap when pasting plain text?

Currently, my goal is to create a visual editor by utilizing the tiptap library. Although v2 of tiptap is more commonly used, there are instances where v1 is necessary. However, I encountered an issue with tiptap's behavior when pasting plain text, ...

Tailwind Component Grid in Action

I'm trying to arrange a list of JavaScript components in a grid with one row and twelve columns. I want to use only six columns for the actual elements, while having three columns of padding on each side of the grid. My goal is to place three elements ...

Following the recent update to IntelliJ IDEA 2022.1.3, the use of ::ng-deep has been marked

After updating the version of IntelliJ, I noticed that the ::ng-deep angular material selector is now marked as deprecated. Here's an example: <mat-form-field class="register-custom-select"> <mat-select formControlName="gende ...

Is it possible to achieve a seamless interaction by employing two buttons that trigger onclick events to alternately

I have a specific goal in mind: I want to create two buttons (left and right) with interactive cursors. The left button should initially have a cursor of "not-allowed" on hover, indicating that it cannot be clicked at the beginning. When the right button ...

An interactive selection tool for a website's navigation bar

Struggling to implement a dropdown menu for my navbar, none of the CSS methods I've tried seem to work. My current HTML code is as follows... <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-t ...

How come setting an optionsValue causes Knockout updating to malfunction?

As I delved into the Knockout tutorials, one particular tutorial caught my attention. Here is the HTML snippet that puzzled me: <h2>Your seat reservations</h2> <table> <thead><tr> <th>Passenger name</th& ...

"An error has occurred stating that the function Factory.function() in AngularJS

I'm a beginner with AngularJS and could use some assistance! My issue involves retrieving JSON data from a URL in a factory function and returning it to the controller. However, I keep getting an error stating that the function doesn't exist. Wh ...

I experienced issues with the brackets software freezing up while using the Bootstrap min CSS file

Recently, I've been using brackets as my text editor and have run into an issue with the bootstrap.min CSS file. For some reason, it keeps freezing whenever I try to load it in brackets. Oddly enough, HTML files work perfectly fine, but ...

Monitor Socket IO for client disconnection events

I am facing an issue where I need to identify when a user loses connection to the socket. It seems that socket.on("disconnect") is not triggering when I simply close my laptop, leading to the ajax call not executing to update the database and mark the us ...

Trouble with $.getJSON while trying to obtain song tempo data with getSongBPM

Still learning the ropes, so bear with me. I am trying to retrieve the BPM of a song using the getSongBPM public API. However, I'm not seeing any data in the console. // Please note that the API key has been updated $.getJSON("https://api.getsongbp ...

`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this: <div>Sample text to check how many lines the text is broken into</div> And the corr ...

ng serve issue persists even after resolving vulnerabilities

Can anyone assist me in resolving why I am unable to start my project after fixing 3 high vulnerabilities? I ran npm audit to identify the vulnerabilities and then used npm install --save-dev @angular/<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

The Toggle Functionality necessitates a double-click action

I'm currently working on implementing a menu that appears when scrolling. The menu consists of two <li> elements and has toggle functionality. Everything is functioning properly, except for the fact that the toggle requires two taps to activate ...

Collecting data with Selenium as elements load [Python]

Is there a way to scrape only the newly generated items in sequence? I have a dynamic list that loads with scrolling. There are two methods I can use to scrape all generated divs: Scroll to the bottom of the list and then scrape all generated divs. Scroll ...

Develop an asynchronous function that can fetch a result at a later time within an Express route

I need to retrieve an Excel file from Box.com using their API and then convert the Excel data into JSON format. Afterwards, I plan to display this JSON data using Express and Handlebars. Below is the function I've created for fetching the Excel file ...

unable to decrease the gap between the rows of the table

I'm currently developing an application that involves a table with rows and columns, along with a checkbox container arranged as shown in the image below: https://i.stack.imgur.com/QoVrg.png One issue I'm facing is getting the letters A, B, C, ...

What is the significance of XmlHttpRequest's readyState being at 2 when receiving a 200 HTTP response

Currently, I am utilizing pure JavaScript (no jQuery) to send a file to the server. The PHP script on the server returns status code 200 upon completion, but the JavaScript is interpreting it as readyState == 2. The PHP code responds with status code 200: ...

How can Codeception/Selenium help in testing the tooltip or customValidity message?

I am trying to implement a feature in my Codeception scenario where I want to validate a form submission with user errors, such as confirming a wrong email address, and display a custom tooltip message in the browser. HTML <form ... > <label ...

The Material UI Menu does not close completely when subitems are selected

I am working on implementing a Material UI menu component with custom MenuItems. My goal is to enable the closure of the entire menu when clicking outside of it, even if a submenu is open. Currently, I find that I need to click twice – once to close the ...

Mastering the Art of Integrating API and JSON!

I've developed a bot using botkit and the Zendesk API to retrieve information. There's a function in my bot that prompts the user for a search term, searches for relevant information using the Zendesk API, and displays the result. I'm faci ...