vlrprbttst vlrprbttst - 1 year ago 65
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

but doesn't work using it this way:



2) how do i make it perform the
function again on click when I remove an item to refresh the number of

Answer Source

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


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