weinde weinde - 24 days ago 8
HTML Question

Meteor random color picker

I wrote this function which should display a random color from this array but it always displays the first one. Is there something wrong with my code? I have tried Googling this and checked the meteor documentation but found nothing useful.

randomInitials: function () {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var nLetter = chars.charAt(Math.floor(Math.random()*chars.length));
var sLetter = chars.charAt(Math.floor(Math.random()*chars.length));
var colors = ["#e57373","#f06292","#ba68c8","#9575cd","#7986cb","#64b5f6","#4fc3f7","#4dd0e1","#4db6ac","#81c784","#aed581","#dce775","#fff176","#ffd54f","#ffb74d","#ff8a65","#a1887f","#e0e0e0","#90a4ae"];

return colors[Math.floor(Math.random()*colors.length)];
return nLetter + sLetter;
},


<div class="other-profile">
<span>{{memberData.profile.initials}}</span>
</div>


Right now it looks like this:
Now

I want this:

This

Answer

Since you are returning only colors, your helper needs to look like

randomInitials: function () {
    var colors = ["#e57373","#f06292","#ba68c8","#9575cd","#7986cb","#64b5f6","#4fc3f7","#4dd0e1","#4db6ac","#81c784","#aed581","#dce775","#fff176","#ffd54f","#ffb74d","#ff8a65","#a1887f","#e0e0e0","#90a4ae"];
    return colors[Math.floor(Math.random()*colors.length)];
},

And in your template:

<div class="other-profile" style="background-color: {{randomInitials}}">
    <span>{{memberData.profile.initials}}</span>
</div>