When Does onRender Trigger


#1

I am rendering an image and want to position a forward and a back arrow at the middle by using the offset of the image relative to the document. I can get this, but what I can’t get is the image’s height. It always gives me 12px.

My question is: How completely has the DOM laid itself out if I can’t get the image height. Here’s some code:

Template.home.onRendered ->
  console.log "in rendered"
  imagePosition = $('img.photo:visible').offset()
  console.log "in rendered, imagePosition is #{imagePosition}"
  console.log "#{selector}: #{imagePosition[selector]}" for selector in ['top', 'left']
  console.log "height is: #{$('img.photo:visible').first().css('height')}"
  middle = imagePosition.top + $('img.photo:visible').first().height() / 2
  console.log "middle is #{middle}"
  $('.previous-slide:visible').offset({left: imagePosition.left + 10, top: middle})

The result of all the log statements is:

in rendered
home.coffee:13 in rendered, imagePosition is [object Object]
home.coffee:14 top: 76
home.coffee:14 left: 85.5
home.coffee:15 height is: 12px
home.coffee:17 middle is 76

So you can see that the height is being seen as 12px when it is 669px, which is what I get if I type $('img.photo:visible').first().css('height') into the Chrome console.

Any hints?


#2

onRendered fires when the template has rendered, so the html in other words. You can’t directly detect when an image has been loaded, however there are options. The most immediate one would be imagesloaded, which has a meteor wrapped version: https://atmospherejs.com/iamkevingreen/imagesloaded

Not sure what the use case would be, but remember there are multiple ways to approach a problem. If you’re getting these properties for positioning of some other element, there might be a better solution using only css. I’ve personally never needed the use for imagesloaded, but you might of course :wink:


#3

This is really useful information. Perhaps there is a pure CSS way to do this but I wasn’t coming up with one, so I thought since I know when the template is rendered, the DOM should be pretty much a known quantity and I could do some arithmetic to put the arrows where I wanted. But, alas, that hasn’t been working out for me. I’ll look at the imagesloaded option. Thanks!