I’m trying to create multiple iron-collapse elements with content inside. I want the iron-collapse to expand when user clicks on a button. The problem is that I can’t get each element expanded individually. The script catches only first element and does not affect the others. I’ve tried many code samples but without success. Can someone help me? My code is below:
var expandContent = document.getElementById('mybutton'); expandContent.onclick = function(event) { var moreInfo = document.getElementById('moreinfo'); var iconButton = Polymer.dom(event).localTarget; iconButton.icon = moreInfo.opened ? 'hardware:keyboard-arrow-down' : 'hardware:keyboard-arrow-up'; /*moreInfo.toggle();*/ /* This one works to, don't know which is better */ event.currentTarget.parentElement.querySelector('iron-collapse').toggle(); };
<paper-card style="width:100%;line-height:56px;font-size:16px;font-weight:400;"> <paper-icon-button class="mybutton" id="mybutton" icon="hardware:keyboard-arrow-up" style="float:right;margin:8px;" > </paper-icon-button> <iron-icon icon="communication:forum"></iron-icon> <iron-collapse id="moreinfo" class="moreinfo" style="width:100%;"> <paper-item> <iron-icon icon="info"></iron-icon> <paper-item-body two-line> <div>Primary text</div> <div secondary>Secondary text</div> </paper-item-body> </paper-item> <paper-item>Second item</paper-item> <paper-item>Third item</paper-item> </iron-collapse> </paper-card>
I want only one collapse to expand after it’s corresponding button is being pressed. Is there way to change this code to achieve what I need, without complete rewrite, because only with this code iron-collapse works properly and changes its attribute expanded=”yes/no”, which I later use with cookies?
Advertisement
Answer
Update Ok, i found proper solution after reading some forums and js docs, i will write it down, maybe someone needs it too.
var elems = document.getElementsByClassName('mybutton'); // Getting all button with same class name for(var i = 0; i < elems.length; i++) { // Adding count indexes to buttons starting from first is 0 elems[i].onclick = function(event){ //And here is function to do expand/collapse, it can be any other function too, main idea was to get work/trigger all items with same class var expandContent = event.currentTarget.parentElement.querySelector('iron-collapse'); var iButton = Polymer.dom(event).localTarget; iButton.icon = expandContent.opened ? 'hardware:keyboard-arrow-down' : 'hardware:keyboard-arrow-up'; event.currentTarget.parentElement.querySelector('iron-collapse').toggle(); console.log("Works ! Great !!!"); } }