Search code examples
jqueryonclickaddclasseachremoveclass

JQuery: Can't removeClass when iterating (.each()) over list items using .on('click')


I am using JQuery to iterate over a ul list, and by using the .on('click'...) I want to add a class to the currently clicked li while removing it from the previously selected li

jsFIDDLE here: jsfiddle link

HTML:

<div id="divisionMenus">
    <ul>
        <li>Type 01</li>
        <li>Type 02</li>
        <li>Type 03</li>
        <li>Type 04</li>
    </ul>
</div>
<p class="results"></p>

CSS:

#divisionMenus {
    width: 220px;
    min-height: 220px;
    position: absolute;
    top: 30px;
    left: 5px;
    background-color: #003399;
}
#divisionMenus ul {
    list-style: none;
    margin: 0;
    padding: 0;
}
#divisionMenus ul li {
    padding: 18px;
    border-top: 3px solid #111;
    font-weight: bold;
    cursor: pointer;
}
#divisionMenus ul li:hover {
    background-color: #c0dde8;
    color: #111;
}
.currentType {
    background-color: #c0dde8;
    color: #111;
}
.results {
    display: none;
}

JQuery:

$(document).ready(function () {

    // select list items in list
    $devisionProductTypes = $('#divisionMenus').children().children();

    $devisionProductTypes.each(function (index) {

        $(this).on('click', $(this), function() {
            $productType = $(this);
            $productTypeTitle = $productType.text();
            $otherProductTypes = $productType.not($(this));

            if (!$productType.hasClass('currentType')) {
                $productType.addClass('currentType');
                $otherProductTypes.removeClass('currentType');

                $('.results').show('fast').text('You have selected ' + $productTypeTitle);
            } else {
                $productType.removeClass('currentType');
                $otherProductTypes.removeClass('currentType');
            }

        });

    });

});

I used the same logic to iterate over some div img in order to toggle the size and it worked there. But not here. Am I missing something or am I approaching this all wrong.


Solution

  • I think you're overcomplicating it, it sounds as simple as:

    $('#divisionMenus li').on('click', function() {
    
      var $this = $(this);
      $this.toggleClass('currentType').siblings().removeClass('currentType');
    
      if ($this.hasClass('currentType')) {
        $('.results').show('fast').text('You have selected ' + $this.text());
      } else {
        $('.results').hide();
      }
    
    });
    

    Here's a fiddle