vlrprbttst vlrprbttst - 6 months ago 18
Javascript Question

counting visible elements on click

i have cart with some items already inside. on load, my script counts how many I have and display it in a div with a number.

each item has a remove button and when i remove an item, i expect my number to update, but it doesn't.

here's my fiddle: https://jsfiddle.net/vlrprbttst/99c8gn7k/7/

i have two questions:

1) i've intentionally put the function outside the document ready function so that i can reuse it. works fine onload using

countItems.init();
but doesn't work using it this way:

$(".remove-item").on("click",function(){
$(this).closest("li").hide();
countItems.init();
});


why?

2) how do i make it perform the
countItems.init();
function again on click when I remove an item to refresh the number of
li
items?

Answer

You are continuously setting the count of visible element when page was loaded. Use the filter() method to get visible elements

Use

var basketItems = $(".cart li"); //Store the reference of element 
var countItems = {
    init: function() {
        //
        var visbleElements = basketItems.filter(":visible").length;
        $(".items").text(visbleElements);
    }
}

Fiddle