I have a ul with multiple list items and am using jQuery to:
- Count the number of list items
- Output that value to a different div
- Change the color of the output text if that value is greater than 13
In a different div, I have multiple buttons with the class .add or .delete. Not surprisingly, clicking these buttons adds or deletes list items.
The jQuery function works perfectly when the page is loaded, but what I’d like to also do is have this count update every time one of the above buttons is clicked.
Here’s my existing code:
var totalItems = $('ul#myList li').length;
$('#outputText').text(totalItems);
if (totalItems > 13) {
$('#outputText').css('color','#F0402B');
};
What do I need to add to make this work? I did look at the answers for this similar question (Run code once on page load, then every time a button is clicked) but they didn’t seem to help. Any help would be greatly appreciated!
Apologies if I’m missing something, but basically: Just wrap the code up in a function, call that function on page load, and also call the function after processing the clicks on the buttons.
E.g.: