Reputation: 31552
I've got code that shows a hidden element and then gets its size:
var div = $('div.foo').show(); // Was hidden.
// Need to wait until the DOM is updated to get its offset
setTimeout(function() {
var offset = div.offset();
bar(offset.top, offset.left);
}, 0);
Is there a cleaner way to do this instead of a deferring the call to div.offset()
with a setTimeout
of 0
, or is this best practice? Can I bind do some DOM update event or something else?
Upvotes: 1
Views: 1362
Reputation: 70199
Calling .show()
without passing a duration parameter is a synchronous action and thus doesn't require a setTimeout
. From the docs:
With no parameters, the
.show()
method is the simplest way to display an element [...]The matched elements will be revealed immediately, with no animation. This is roughly equivalent to calling
.css('display', 'block')
, except that the display property is restored to whatever it was initially.
If you specify a duration however, you can pass a callback function which will be executed when the animation completes:
var div = $('div.foo').show(400, function() {
var offset = $(this).offset();
bar(offset.top, offset.left);
});
Upvotes: 3