whitney
whitney

Reputation: 31

jQuery .on('click') only works once

I'm trying to make a glyphicon in the <th>'s indicate whether you're sorting by ascending or descending values. The original glyphicon displayed is "glyphicon-menu-up".

<table class="table ws-table-list table-hover">
<thead class="hidden-sm hidden-xs">
    <tr>
        <th class='hidden-sm hidden-xs'>
            <span class="glyphicon glyphicon-menu-up"></span>
            @Ajax.ActionLink("Amount", Model.PagedData.ActionMethod, new { pageNumber = Model.Number + 1, sortColumn = "amount", sortAscending = Model.PagedData.SortAscending, previousSortColumn = Model.PagedData.PreviousSortColumn }, new AjaxOptions
                {
                    HttpMethod = "GET",
                    InsertionMode = InsertionMode.Replace,
                    UpdateTargetId = Model.PagedData.UpdateTargetId
                })
        </th>
    </tr>
</thead>
...
</table>

I've gotten the jQuery on('click') function to work (changing into "glyphicon-menu-down"), but it only works once. Not only that, but when the data is sorted, the glyphicon automatically reverts back to the "glyphicon-menu-up" after ~0.5 seconds by itself. (Could this have something to do with the @Ajax.ActionLink function?)

I've tried all the answers I could find on this site, including .on, .off, .delegate, e.preventDefault, and this format:

$('.ws-table-list').on('click', 'th', function() {
     console.log('click');   // This only runs once in the console
     $('span', this).toggleClass('glyphicon-menu-up glyphicon-menu-down');
}); 

I'm sure the answer is super simple but I'm just not getting it I guess. Any help will be greatly appreciated.

Upvotes: 2

Views: 1008

Answers (1)

dokgu
dokgu

Reputation: 6080

Try to change where you put your event listener:

$('body').on('click', '.ws-table-list th', function() {
     console.log('click');   // This only runs once in the console
     $('span', this).toggleClass('glyphicon-menu-up glyphicon-menu-down');
}); 

Upvotes: 1

Related Questions