Rick Roles: Collapse

by JamesKyle

HTML

<link rel="stylesheet" href="http://cdn.thejameskyle.com/bootstrap.css">
<link rel="stylesheet" href="http://cdn.thejameskyle.com/bootstrap-responsive.css">
<ul data-role="collapse">
  
    <h4 data-subrole="title">Never Gonna..</h4>
    
    <li data-subrole="initial">
        <a href="#">Give you up</a></li>
    <li data-subrole="initial">
        <a href="#">Let you down</a></li>
    <li><a href="#">Run around and desert you</a></li>
    <li><a href="#">Make you cry</a></li>
    <li data-subrole="initial">
        <a href="#">Say goodbye</a></li>
    <li><a href="#">Tell a lie and hurt you</a></li>
    
    <hr data-subrole="ignore">
    
    <div data-subrole="expand">
        <a href="#" data-alt="See Less">See More</a>
    </div>
    
</ul>

CSS

[data-role="collapse"] > * {
    display: none;
}

[data-role="collapse"] [data-subrole="title"],
[data-role="collapse"] [data-subrole="expand"],
[data-role="collapse"] [data-subrole="initial"],
[data-role="collapse"] [data-subrole="ignore"],
[data-state="expanded"] > * {
    display: block;
}

JavaScript

var collapse = $('[data-role="collapse"]')
                    .attr('data-state', 'collapsed')
                    .find('[data-subrole="expand"]');

collapse.click(function(e) {
    
    e.preventDefault();

    var $this = $(this).parent('[data-role="collapse"]'),
        alt = $this.find('[data-alt]');
    
    alt.each(function() {
        var $this   = $(this),
            text    = $this.text(),
            newText = $this.attr('data-alt');
        
        $this.attr('data-alt', text).text(newText);
    });
    
    if ($this.attr('data-state') === "expanded") {
        $this.attr('data-state', 'collapsed');
    } else {
        $this.attr('data-state', 'expanded');
    }
    
});