Search code examples
jqueryhtmltwitter-bootstraptogglebutton

Can I Toggle content of Element based on pixel height of element?


Using Bootstrap 2.3.2 I've previously used a toggle button to show and hide text using the Collapse plugin but from what I see it only allows me to reveal and hide the entire contents of an element.

What I need is to already have 170px of the element's content visible and then when the button is clicked, it reveals the rest of the text in the element - but I need to do this without adding any additional elements, it needs to be based on height.

Is this possible with Bootstrap? Or if not, jQuery?


Solution

  • This can be done using CSS for the element styling and then applying classes via Javascript:

    The HTML:

    <div class="toggle">
    your huge text here...
    </div>
    

    CSS:

    .toggle{
        height:170px;
    }
    .open{
        height:auto;
    }
    

    and JS (using jQuery):

    $('.toggle').on('click', function () {
        $(this).toggleClass('open');
    });
    

    What the script basically does is detect when you click on the .toggle and, if it is clicked, then it toggles the class .open which sets the propertie height to auto, leading the element with the text to be as huge as it can grow.

    Here is a working example: http://jsfiddle.net/8SXNZ/1/