Handling toggled onclick with JQuery

I have a piece of text that I want to show truncated, but when clicked, it will expand to show the rest. Pressing it again should truncate it.

I tried to use the onclick event to handle it like this ( WARNING : don't run the following code without reading below ...):

<span id='blah' onclick='showAllComment("this is a long comment to see it all", 9, true )'>this is a...</span>

<script>
function showAllComment( comment, shortCommentLen, showFullComment )
{
    alert( $("#blah").html() );

    if( showFullComment )
    {
        $("#blah").html( comment );
        $("#blah").click( showAllComment( comment, shortCommentLen, false ) );
    }
    else
    {
        $("#blah").html( comment.substring( 0, shortCommentLen ) + "..." );
        $("#blah").click( showAllComment( comment, shortCommentLen, true ) );
    }
}
</script>

      

But as you will see, it calls itself many times and you have to complete the task with the browser (so be careful when running this code !!!!)

Can anyone suggest why this is happening and what to do to resolve it.

Thank you in advance

+1


source to share


2 answers


This is because you are calling the function recursively showAllComment

Try doing something like this:



function showAllComment( comment, shortCommentLen, showFullComment )
{
    alert( $("#blah").html() );

    if( showFullComment )
    {
        $("#blah").html( comment );
        $("#blah").click( function () { showAllComment(comment, shortCommentLen, false);} );
    }
    else
    {
        $("#blah").html( comment.substring( 0, shortCommentLen ) + "..." );
        $("#blah").click( function () {showAllComment( comment, shortCommentLen, true );} );
    }
}

      

This way you include the call inside the anonymous function, so it will be triggered after only the element is clicked #bla

.

+3


source


Users without javascript enabled will not be able to read the comment. A better approach would be to include the entire comment in span

and make the javascript truncate it on page load:

JavaScript:

$(function() {
    $(".blah").each( function() {
        var shortCommentLen = 9;
        var comment = $(this).html();                   
        $(this).html(shortComment(comment, shortCommentLen));
        $(this).toggle(
            function() { $(this).html(comment); },
            function() { $(this).html(shortComment(comment, shortCommentLen)); }
        );

        function shortComment(comment, shortCommentLen) {
            return comment.substring( 0, shortCommentLen ) + "...";
        }
    });
});

      



HTML:

<span class='blah'>this is a long comment to see it all</span>

      

The function toggle(fn1, fn2)

is separated between the two functions when the item is clicked.

+2


source







All Articles