physicsboy
physicsboy

Reputation: 6326

convert jQuery code to Polymer?

Would it be at all possible to convert some JQuery into PolymerJS?

Problem: Wanting a certain CSS class to only be applied to the element being clicked.

I had it working in JQuery, but wondering if it could be done in Polymer? I know how to add and remove CSS from the active element, just not how to remove from all elements except the active one.

Component being applied to

 <iron-ajax id="userGet"  handle-as="json"  method="GET" on-response="setUser"></iron-ajax>
    <div class="iron-list-container">
         <iron-list id="list" items="setUser" as="user" >
            <div class="item" id="item">
                 <!-- USER INFO STUFF GOES HERE -->
             </div>
         </iron-list>
    </div>

GIF of functionality I have with the JQuery

JQuery

toggleLeftBorder: function() {
    $(".item").click(function() {
        $('.item').removeClass('addBorderLeft');
        $(this).addClass('addBorderLeft');
    })
},

PolymerJS so far

toggleLeftBorder : function() {
    /* this line will add the necessary css class to selected elements */
    this.$.item.classList.add('addBorderLeft');
},

Upvotes: 1

Views: 280

Answers (1)

zacharytamas
zacharytamas

Reputation: 1039

There's not a one-liner to do this in Polymer like jQuery provides. Polymer tries to be as light-weight as possible and doesn't add very many DOM manipulation tools.

An equivalent line in vanilla JS might be:

this.shadowRoot.querySelectorAll('.addBorderLeft')
    .forEach(item => item.classList.remove('addBorderLeft');

Since you only want one item selected at a time you could just keep track of the previously selected item and remove the class from it before you set the newly selected one:

toggleLeftBorder : function() {
  if (this.selectedUserElement) {
    this.selectedUserElement.classList.remove('addBorderLeft');
  }

  this.selectedUserElement = this.$.item;
  this.selectedUserElement.classList.add('addBorderLeft');
},

However, since you're using iron-list it comes with selection baked in so you should be able to do this declaratively like this:

<iron-ajax id="userGet"  handle-as="json"  method="GET" on-response="setUser"></iron-ajax>

<div class="iron-list-container">
  <iron-list id="list" items="[[setUser]]" as="user" 
    selection-enabled selected-item="{{selectedUser}}">
    <div class="item">
      <!-- USER INFO STUFF GOES HERE -->
    </div>
  </iron-list>
</div>

This would do the following:

  • Create a property on your element called selectedUser which is always the currently selected User. I suspect you need this elsewhere in your element/application anyway.
  • Add the selected class to the selected iron-list item. Note that this is different from your addBorderLeft class so you'd need to put your styles on .selected instead.

Upvotes: 1

Related Questions