Search code examples
polymer-1.0custom-element

How to declare a property that will add a css class to my custom-element in Polymer 1.0


I make a custom-element which is a simple card whith some caption on it. The problem is, that i dont know how to declare a property that will add a css class to make the background-image url different between each card.

I love Polymer, i can create great things, but my limit is the little knowledge of javascript, so please help? Here is some code =)

<dom-module id="gallery-card">
 <template>

 <style>
  :host {
  display: block;
  }
  .container{
  height: 50px;
  }
  .card{
  width: 98%;
  height: 98%;
  overflow: hidden;
  position: relative;
  cursor: pointer;
  }
/* Classes to add*/
  .card.project_1{
  background-image: url(../img/project01.jpg);
  }
  .card.project_2{
  background-image: url(../img/project02.jpg);
  }
  .card.project_3{
  background-image: url(../img/project03.jpg);
  }
  paper-ripple{
  color: #1936ce;
  }
  #caption {
  width: 50%;
  height: 80px;
  background-color: #0c0c0c;
  overflow: hidden;
  }
 </style>

 <div class="container">
  <div class="card">
   <paper-ripple centers></paper-ripple>
   <div id="caption">
    <h1>{{title}}</h1>
    <h2>{{description}}</h2>
   </div>          
  </div>
 </div>
</template>


<script>
// element registration
Polymer({
is: "gallery-card",

properties:{
  title: String,
  description: String,
}
});
</script>
</dom-module>

what should i do, to bring my cards and make them different from each?


Solution

  • Use a computed binding on the card div like:

    <div class$="[[_computedClass(index)]]">
    

    And then in your Polymer element:

    _computedClass(value) {
      return 'card project_' + value;
    }
    

    So ideally you'd have something like:

    <template is="dom-repeat" items="[[cards]]">
       <div class$="[[_computedClass(index)]]">
       <paper-ripple centers></paper-ripple>
       <div id="caption">
        <h1>{{title}}</h1>
        <h2>{{description}}</h2>
       </div>          
      </div>
    </template>
    

    See the docs.