Animating jQuery UI with an initially undefined height

Check out this fiddle:

[edit: updated fiddle => http://jsfiddle.net/NYZf8/5/ ]

http://jsfiddle.net/NYZf8/1/ (try viewing in different screen sizes to ensure the image fits inside the %-width div)

The animation should begin from where the image is correctly positioned after the animation completes. I am puzzled as to why the initial call to setMargin() results in a negative margin even though the logged heights of the container div and img are the same, and only after the jqueryui show() call does the image appear where I want it to be from the start. My suspicion is that somehow the height of the image is 0 or undefined despite logging fine :?

Javascript code:

console.log('img: ' + $('img').height());
console.log('div: ' + $('div').height());

$('img').show('blind', 1500, setMargin);

function setMargin() {
    var marginTop =
    ( $('img').closest('div').height() - $('img').height() ) / 2;

    console.log('marginTop: ' + marginTop);

    $('img').css('marginTop', marginTop + 'px');
}

setMargin();

Answer №1

Curious dilemma...after experimenting with your code for a while (latest update), I noticed that the blind animation wasn't triggering in my browser (I'm using Chrome, so maybe it was running but not visible since the image was always displayed), so I decided to move it inside the bound load function:

$('img').bind('load', function() {
    ...
    $(this).show('blind', 500);
});

Once the animation started, it seemed to 'snap' or 'jump' after completion and appeared with an incorrect margin. This suggests that jQuery may struggle to calculate dimensions of items not yet displayed on screen. Additionally, blind appears to require more specific dimensions to work properly. Thus, the issue at hand: how do you determine elements' rendered dimensions before they appear on screen?

One approach is to slightly fade in the element whose dimensions need calculation - imperceptibly at first - perform calculations, hide it again, and prepare it for the appearance animation. This can be accomplished using jQuery's fadeTo function:

$('img').bind('load', function() {

    $(this).fadeTo(0, 0.01, function() {

        // carry out calculations...

    }
}

You'd have to establish dimensions, apply them with the css() function, animate the image blind, and then revert the styles back to their original state, all due to the explicit dimension requirements of the blind animation. Using classes in the css could help manage this process more effectively. Check out this detailed working example: jsfiddle working example

This method may not be the most elegant, but it's a good starting point. There are simpler ways to achieve better results, so why the interest in executing image blinds and precise alignments this way? It appears to be quite challenging with the current code...anyway, hope this information proves useful! :)

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

Creating nested tabs using vanilla JavaScript, no need for jQuery

I am currently working on implementing tabs using a JavaScript function. The issue I am facing is that when I try to have tabs within one of the tabs, everything disappears every time I click on one of the inner tabs. This happens because the JavaScript fu ...

Customizing the scrollbar within a modal using reactjs-popup

I am currently working on a CustomPopup functional component that includes a reactjs-popup: function CustomPopup({setFalse, item}){return(<Popup open={true} onClose={() => {setFalse(false)}} modal closeOnDocumentClick nested> {item === "howto ...

A guide on expanding MaterialUI Accordion in React by clicking on a different component

I am trying to implement a feature where clicking on a marker on a map will expand the corresponding accordion item. Both markers and accordion items have matching key values as seen in the screenshot below. https://i.sstatic.net/PAxOO.png The code I cur ...

After installing Ember and running the Ember server, I noticed that the node_modules directory appears to be empty. This issue is occurring on my Windows 10 x64 PC

Welcome to the command console: C:\Users\Documents\emberjs>ember server node_modules seem to be empty, consider running `npm install` Ember-cli version: 2.14.2 Node version: 6.11.2 Operating System: Windows 32-bit x64 I'm a beg ...

Error in syntax JSONLoader

I am attempting to bring my models from Cinema 4D into three.js. I have used the OBJLoader successfully. If I try to convert my exported wavefront (.obj) file with convert_obj_three.py, it generates a json-file without any errors. However, when I try to l ...

Executing PHP function through AJAX

I have thoroughly researched various resources regarding my issue but still have not been able to find a solution. My goal is to retrieve the result of a PHP function using jQuery AJAX. function fetch_select(){ val_name = $('#name').val(); ...

Ensure that the Accept header is included in the JQuery AJAX GET request when using JSONP

My attempt to include an accept header in a jQuery AJAX GET request using the "jsonp" dataType is not working as expected. Here's my current code: var e4json = JSON.stringify( { "thomas_smith106" : "Daniel244", ...

Make sure that you always return true whenever a button is clicked while using the jQuery dialog feature

Currently, I am utilizing a jQuery dialog box. Upon clicking the Button, a popup is triggered, but it returns true and executes the server-side event of the button. My goal is for the return value to be true when the user clicks on "Yes" and false when th ...

React component not consistently returning correct results due to undefined values being included

Currently, I have a function that iterates through one array, comparing its values with those in another array. When it finds a match, it adds the matching results to a new array called addToState. These matches are then concatenated with the original arra ...

Using setTimeout within a loop to prevent any blocking operations

Here are some code snippets to illustrate my question: var webSocketsServerPort = 8002; var webSocketServer = require('websocket').server; var conns = []; I populate the array conns with users' information after they successfully connect, ...

Discovering the lengthiest strings in a multi-dimensional array using JavaScript

let lists = ["Grocery", "Clothing", "Furniture"]; let items = [ [ "tomatoes", "cheese", "bread", "ham" ], [ "shirt", "jacket", "jeans" ], [ "sofa", "carpet", "bed" ] ]; These two arrays are connected in ...

Is there a way to determine if a table cell contains overflowing text compared to another cell?

https://i.sstatic.net/IYafA.png Is there a way to detect if the content of the fourth td overflows from the second td? I am looking for a method to determine which td has overflowed text and identify which td's text is overflowing. What approach ca ...

Is it possible to load a jQuery Mobile page from a separate domain?

How can I load a jQuery AJAX Enabled page from an external source? I am developing an app using phonegap and one of the pages needs to be hosted online for real-time updates. However, I have been unable to figure out how to accomplish this so far. Simply ...

Using jQuery each with an asynchronous ajax call may lead to the code executing before the ajax call is completed

In my jQuery script, I utilize an each loop to iterate through values entered in a repeated form field on a Symfony 3 CRM platform. The script includes a $.post function that sends the inputted value to a function responsible for checking database duplicat ...

Guidelines for arranging nested divs in a CSS grid for a flat display

When using vue.js, I create a table from an object that should have two columns. Each column is generated from the key and value of the object. Here is the equivalent HTML: <div id="table"> <div> <div> this is something long ...

My goal is to dynamically adjust the height of this section based on its content

I experimented with this code snippet: <section class="unique"> <div class="this d-flex pt-5"> <div class="leftside2 w-50 h-100"> <img src="images/twowomen.jpg" alt=" ...

Angularjs $state.go is a powerful tool for navigating through different states

I've been working on setting up a basic navigation system for my single-page application. It consists of a series of links in a list, each linked to a method in a NavigationController. The method then triggers $state.go by passing it a state string. I ...

The unexpected occurence of the Onbeforeunload exception

I am attempting to create an exception for onbeforeunload and display a warning about potential data loss whenever the quantity is not zero: Here is what I have tried so far: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www. ...

What is the best way to stretch my background image to cover the entire screen?

I am working on a Python Django project and I want to create a full-screen background. The HTML code: { % load static %} <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags--> <meta charset=" ...

CSS styling not functioning properly

After spending a considerable amount of time on this issue... <div id="pager" style="top: 5px; position: relative; " class="pager" > <form> <img src="http://tablesorter.com/addons/pager/icons/first.png" alt="first" class="first" ...