JohnAllen
JohnAllen

Reputation: 7531

Add attribute to class using Meteor-Blaze

How do I do the below using Meteor + Blaze and/or why won't this work?

Code does/doesn't do what it says below

// client...

$(document).ready(function () {
  console.log("this logs...");
  $('a.external').each(function () {
    console.log("this doesn't log");
    $(this).attr('title', 'External Link');
  });
});

Upvotes: 0

Views: 723

Answers (1)

Tarang
Tarang

Reputation: 75985

In Meteor you need to be careful to manipulate your DOM after its drawn. The above code would fire when all the scripts have downloaded, but the DOM hasn't been drawn yet.

Luckily this is super easy!

If your template is this

<template name="hello">
    <a href="https://servicelocale.com/" class="external">Link</a>
</template>

Then you can use the rendered callback:

Template.hello.rendered = function() {
    this.$('a.external').each(function () {
        $(this).attr('title', 'External Link');
    });
}

I also used this.$ instead of $ in the rendered callback. This is useful because it only looks in the hello template instead of all over. So you can have <a class="external" on your page, but in a different template, and it wouldn't have the title attribute added.

You can use $ instead here as well.

Upvotes: 2

Related Questions