Tuesday, November 26, 2013

Working with Bootstrap & JavaScript in a Foreach Loop

Bootstrap is an open-source frontend framework developed by Twitter that provides web developers with a large selection of HTML, CSS & JavaScript components that can save time in the early stages of putting a user interface together.

A couple of the Bootstrap JavaScript components I've used while here at camp are the Modal and the Collapse. A modal is a dialog box or prompt that can be used for a variety of things, and hides the content within the modal body until it is triggered by a button or link. A collapse is more like a Panel, that's been modified to act like a drawer for content, opening when the panel header link is clicked.
Collapse Example from GetBootstrap.com
These are pretty handy UI bits, but they can be tricky when you use them within a foreach loop to populate a page with dynamic database-driven content. On the Goalizr Goals page I wanted to use a Collapse to show a list of Activities associated with each goal. Once I got the code for displaying the Activities in the controller and the view (Thanks for the help, David Graham!), I was ready to implement the Collapse in the loop. But when I ran the application only the first collapse for the first goal worked. The others would actually toggle the collapse for the first one.

Code for Goal Activities Panel
We ran into this problem with Fund.io, and Mark Grunden (who is now an Assistant Counselor, btw!) helped me come up with a solution. In the example above, I have replaced the default IDs and references with Razor calls on the GoalId. This creates a unique ID for every Collapse on the page, allowing all information to be displayed properly when the Collapse header is clicked.


No comments:

Post a Comment