Access dom-repeat element's CSS class on tap

616 views Asked by At

My dom repeat displays a list of icons which I can bookmark or unbookmark ,which generating dom-repeat I call a function to find if this icon is bookmarked or not,that will return CSS class

 .book-marked {
    color: red;
  }

  .not-book-marked {
    color: green;
  }

  <template is="dom-repeat" items="{{membersList}}">    
        <iron-icon icon="bookmark" class$="[[_computeBookMark(item.userId)]]" on-tap="_toogleBookMark"></iron-icon>     
  </template>

Once I get all my list of icon now if user click that icon I need to toogle css class.so I wrote on-tap function

  _toogleBookMark:function(e) {
    var userData = e.model.item;  //gets entire data object of that element
    var index = e.model.index;    //gets index of that element
  },

I can't use ID since its dom-repeat ,Is there any other ways so that I can change CSS of that dom-repeat element in _toogleBookMark() function on clicking? or is it possible to change CSS with index??or using "e" reference in _toogleBookMark(e) function !!

2

There are 2 answers

0
Daniel Radliński On BEST ANSWER

Not sure if I understood correctly - you want to access the element you've tapped?

Just use the event.target property then. It will return the element on which the event happened, in this case, the icon you have tapped.

_toogleBookMark = function(e) {
e.target.classList.toggle("not-book-marked");

}

Check this example.

Mind you:

1) When using Shady DOM, assuming our element is a custom element, target can be a component from the element's template, not the element itself. To prevent that, use Polymer.dom(e).localTarget (read more here).

2) When using a custom element with light DOM children, the above may not be enough, your (local)target will be a light DOM child, not the element you wished for. In that case, use Element.closest(selector) to (optionally) go up the DOM to the element you want. Read more about the method here.

1
webmonkey On

As you just want to swap your class on tap, do it like this:

Add an own attribute, like data-id="1" and the id attribute, but be sure they have the same value:

<template is="dom-repeat" items="{{membersList}}">    
    <iron-icon icon="bookmark" class$="[[_computeBookMark(item.userId)]]" on-tap="_toogleBookMark" data-id="{{item.userId}}" id="{{item.userId}}"></iron-icon>     
</template>

Now, inside your _toggleBookMark function, you can access the current tapped element and swap CSS classes by:

_toogleBookMark:function(e) {
    // this gives you your userId from the data-id attribute
    var userId = e.path[0].dataId; 

    // we can access the element now with
    var element = this.$$('#' + e.path[0].dataId);

    if (element.classList.contains('book-marked')) {
      element.classList.remove('book-marked');
      element.classList.add('not-book-marked');
    } else {
      element.classList.add('book-marked');
      element.classList.remove('not-book-marked');
    }
},