verbatross
verbatross

Reputation: 607

Meteor onRendered - difficulty accessing DOM

I'm having trouble accessing the DOM from within a Template onRendered block in Meteor. Here is a simplified version of the template html:

<template name="templateName">
  {{#each thing}}
    <img src="{{filename}}">
  {{/each}}
</template>

And here is the client JavaScript code:

Template.templateName.onRendered(function() {
  console.log('check');
  this.$('img').each( function() {
    console.log('hi');
  });
});

I have verified that the code is running, as the 'check' appears in the browser console, but none of the 'hi's are printed despite several images displaying.

In case there is a better alternate way to go about this in general, the goal here is to resize images using information from the DOM.

To confirm, the jquery package is added to Meteor.

Thank you in advance for any help you can provide! I've been stumped for several hours on this deceptively simple issue.

Upvotes: 1

Views: 745

Answers (3)

Little Brain
Little Brain

Reputation: 2837

Here's what worked for me:

Template.imgTmpl.events({
  "load img": function(event){
    console.log("width " + event.currentTarget.naturalWidth);
    console.log("height " + event.currentTarget.naturalHeight);
  }
});

Upvotes: 0

saimeunt
saimeunt

Reputation: 22696

Follow up: I'm trying to get the (natural) width and height of the image within the onRendered function, but it's returning 0, indicating that while the template has rendered the images aren't yet loaded. How can I wait for the images to load?

Completing @juliancwirko answer, now that you have a separate template for defining your images list items, you can listen to the load event on the img tag using Meteor event maps.

Template.imgTmpl.events({
  "load img": function(event, template){
    console.log("image width :",this.$("img").prop("width"));
    console.log("image height :",this.$("img").prop("height"));
  }
});

Upvotes: 0

juliancwirko
juliancwirko

Reputation: 1282

You shouldn't use jQuery each in your onRendered parent template. Instead you can do something like:

<template name="templateName">
    {{#each thing}}
        {{> imgTmpl}}
    {{/each}}
</template>

<template name="imgTmpl">
    <img src="{{filename}}">
</template>

js:

Template.templateName.onRendered(function() {
    console.log('check');
});

Template.imgTmpl.onRendered(function() {
    console.log('hi');
});

Upvotes: 1

Related Questions