Search code examples
javascriptjqueryfunctionjspexpander

How to set div's id with jQuery function?


I receive list of feed items from Servlets

<c:forEach items="${feedItemsList}" var="feedItem">
    <table class="contentItem">
        <tr>
            <td>
                <div id="block">
                    <a id="" href="javascript:showFeedItem(${feedItem.id});"><c:out
                            value="${feedItem.title}" /></a>
                </div>
                <div class="feedItemExpander" id="${feedItem.id}">...My
                    info...</div>
            </td>
        </tr>
    </table>
</c:forEach>

I want to expand and collapse div with id=${feedItem.id}. Clicking on

<a id="" href="javascript:showFeedItem(${feedItem.id});"><c:out
                            value="${feedItem.title}" /></a>

I pass ${feedItem.id} to jQuery function. Then showing div with id=${feedItem.id}. My function:

function showFeedItem(feedItemId) {
            $('.feedItemExpander').each(function(index) {
            if ($(this).attr("id") == feedItemId) {
                $(this).show(200);
            }
        });
    }

How to collapse it by second click on the same link?


Solution

  • To hide it by clicking on the same link, do a check to see if the element is visible and then either hide or show it based on that:

    function showFeedItem(feedItemId) {
        $('.feedItemExpander').each(function(index) {
            if ($(this).attr("id") == feedItemId) {
                if (!$(this).is(':visible')) $(this).show(200);
                else $(this).hide(200);
            }
        });
    }