Increase the count of list items after deleting one by clicking on a button

After removing one item from my list, the total count is not being updated. How can I update the total number of items in the list after removing one?

var totalList = document.getElementById('total');
var deleteBtn = document.getElementsByClassName('delete');
var allList = document.querySelectorAll(".navbar-nav li");
var removeNotify = function(e) {
    e.preventDefault();
  var notifyItem = $(e.delegateTarget).parent();
  var html = $('html');
  html.css('overflowX', 'hidden');
  notifyItem.addClass(notifyItem.data('animation-class'));
  notifyItem.bind('oanimationend animationend webkitAnimationEnd', function() {
    notifyItem.remove();
    html.removeAttr('style');
  }); 
};
$(function() {
  $('.delete').on('click', removeNotify);
  console.log(allList.length - 1);
  
});
// total li
var myList = document.getElementById('myList');
$('.delete').on('click', 'li', function(ev){ 
  totalList.innerHTML = allList.length - 1
});
.navbar-expand-lg .navbar-nav {
    -ms-flex-direction: column;
    flex-direction: column;
}
.nav-scroller {
    position: relative;
    z-index: 2;
    height: 2.75rem;
    overflow-y: hidden;
}
.nav-scroller .nav {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-wrap: nowrap;
    flex-wrap: nowrap;
    padding-bottom: 1rem;
    margin-top: -1px;
    overflow-x: auto;
    text-align: center;
    white-space: nowrap;
    -webkit-overflow-scrolling: touch;
}
.nav-item {
  text-align: left;
  padding-left: 2rem;
  border-bottom: 1px solid #252629;
  padding: 1rem 2rem;
  position: relative;
  -webkit-transition: .1s all ease-in-out;
  transition: .1s all ease-in-out;
}
.navbar-nav .title {
  font-family: "Monda-Regular", sans-serif;
  line-height: 1.75rem;
  letter-spacing: .05rem;
}
.nav-item:hover:not(:first-child){
  background-color: #4362B1;
}
.nav-item:hover p,
.nav-item:hover .date {
  color: #E1E2E2;
}
.nav-item .delete {
  display: block;
  width: 16px;
  height: 16px;
  line-height: 15px;
  font-weight: bolder;
  position: absolute;
  top: 10px;
  right: 10px;
  border-radius: 50%;
  cursor: pointer;
  background-color: #637cbb;
  visibility: hidden;
  -webkit-transition: .1s all ease-in-out;
  transition: .1s all ease-in-out;
}
.nav-item:hover .delete {
  visibility: visible;
}
/*li animation on delete*/
@-webkit-keyframes minimize {
  0% {
    max-height: 10rem;
    padding-top: 1rem;
    padding-bottom: 1rem;
    border-width: 1px;
    overflow: hidden;
  }
  100% {
    max-height: 0;
    padding-top: 0;
    padding-bottom: 0;
    border-width: 0;
    overflow: hidden;
  }
}
@keyframes minimize {
  0% {
    max-height: 10rem;
    padding-top: 1rem;
    padding-bottom: 1rem;
    border-width: 1px;
    overflow: hidden;
  }
  100% {
    max-height: 0;
    padding-top: 0;
    padding-bottom: 0;
    border-width: 0;
    overflow: hidden;
  }
}
.navbar-nav li.minimize {
  -webkit-animation-duration: .5s;
          animation-duration: .5s;
  animation-iteration: 1;
  -webkit-animation-fill-mode: forwards;
          animation-fill-mode: forwards;
}
.navbar-nav li.minimize {
  -webkit-animation-name: minimize;
          animation-name: minimize;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <div class="notifyNum align-center d-flex justify-content-center align-items-center mr-auto">
          <span id="total" class="fontSize12"></span>
        </div>
<ul id="myList" class="navbar-nav w-100 align-left">
              <li class="nav-item title">
                <h1 class="p-0 m-0 weight700 fontSize20 gray6">Notifications</h1>
              </li>
              <li id="1" class="nav-item" data-animation-class="minimize">
                <h2 class="notifyTitle weight600 fontSize16 gray5 mb-2">test-1 </h2>
                <span class="delete text-center">&times;</span>
              </li>
              <li id="2" class="nav-item" data-animation-class="minimize">
                <h2 class="notifyTitle weight600 fontSize16 gray5 mb-2">test-2 </h2>
                <span class="delete text-center">&times;</span>
              </li>
              <li id="3" class="nav-item" data-animation-class="minimize">
                <h2 class="notifyTitle weight600 fontSize16 gray5 mb-2">test-3 </h2>
                <span class="delete text-center">&times;</span>
              </li>
            </ul>

I've been trying to update the total count of my lists and display it in a div using the following code, but it's not working:

var myList = document.getElementById('myList');
$('.delete').on('click', 'li', function(ev){ 
  totalList.innerHTML = allList.length - 1
});

Answer №1

Access the allList selector within the on-click function to ensure it is updated properly each time you click on delete.

Here's a simple solution to achieve the desired functionality:

Replace

totalList.innerHTML = allList.length - 1
with:

$('.delete').on('click', function(ev) {
  totalList.innerHTML = document.querySelectorAll(".navbar-nav li").length - 1
});

Check out the demo here

Side note: It seems that you are not excluding the .title list element from the allList. This might result in totalList always displaying 1, even after deleting all "test" items...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide to customizing Highcharts for extracting targeted JSON information

I've been dedicating a significant amount of time trying to unravel this puzzle. Typically, I prefer researching solutions rather than posing questions, but this challenge has me completely perplexed. My goal is to generate a Highchart using data from ...

Refreshing an iframe located on disparate domains

There is a webpage called "main.jsp" within the domain "domain1". This page contains an iframe that loads content from another domain known as "domain2". Essentially, "main.jsp" serves as a common content platform, with the iframe displaying content from v ...

Experiencing frequent rerendering in React following the incorporation of socket io functionality

Currently working on a project similar to Omegle, take a look at some of the code below focusing on the useEffect functions. const Messanger =(props)=>{ let socket = props.socket; let intro; const myId = socket.id; const [readOnly,setReadOnly] = useSta ...

Is it possible to include a variable in the name of my hook state?

My idea is to use the hook in a way that allows for usage like this <Foo id="foo1" /> and <Foo id="foo2" /> export const Foo = () => { const [state + props.id, state + props.id] = useState("foo") return ( ...

React-Query: executing a function after updating query data

After updating the cache in a form, triggered by a response from the server, I utilize setQueryData. However, following this cache update, my goal is to refocus on the form input field. Here are some details: Within my React application, I employ Recoil. ...

Sending Additional Information to the Script in jQuery UI Sortable

Currently, I have successfully sorted a table as shown below: var someVar = 'some var'; // AJAX function for sorting $('table#pages tbody').sortable({ items: "tr:not(.first)", update: function() { var i ...

I am currently encountering an issue with a code snippet that is not performing as anticipated and require clarification

import React, {useEffect, useState} from 'react'; export function App(props) { let [state, setState] = useState(2); console.log('outside', state); useEffect(()=>{ document.querySelector('.btn').addEventListener( ...

Did I incorrectly associate the function with the button causing it to always be executed?

I am working on a PHP page, where I have some initial content followed by session initialization code: <?php session_start(); ?> The requirement is to display a disconnect button only if the user is logged in, indicated by the presence of $_SESS ...

create a gentle appearance for an element

I am looking to replicate the visual appearance of each page on this particular website: There is something about the lighting that I really admire. I have attempted to recreate the animation, but I have been unsuccessful in my attempts. Any assistance wo ...

Angular triggers a function upon completion of several API requests

I am currently working on an Angular service that involves making HTTP calls. Here is an overview of the code structure: this.checkAndSendNotifications = function() { UsersService.getArray(function(array) { var notifications = []; angu ...

Is there a way to create HTML code from a portion of my Angular2 template?

I am looking for a way to enable my users to easily copy and paste the HTML output of a component template into platforms like MailChimp or their personal website. Similar to how some websites have buttons to generate embeddable iframe codes, I want to pro ...

checkbox inspired by the design of the iPhone

I'm looking to create a custom checkbox! <label id="sliderLabel"> <input type="checkbox" /> <span id="slider"> <span id="sliderOn">SELECTED</span> <span id="sliderOff">SELECT</span> ...

Updating during an ongoing state transition is not possible, especially within the `render` method. The `render` method should strictly be a pure function based on the props and state provided

Currently, I am utilizing react and react hooks for the front-end development of my project. Unfortunately, I have encountered an error message that states: index.js:1 Warning: Cannot update during an existing state transition (such as within `render` ...

I am interested in using AngularJS to redirect to a different page

I am looking to navigate to another page within the application, similar to how it is done in MVC or asp.net applications. Below is the Route.js file that I have defined. The route.js file is structured as follows: var MainApp=angular.module('Routin ...

Improving efficiency for handling a vast number of inputs in React applications

Dealing specifically with Material UI, I am faced with the challenge of rendering a large number of inputs (more than 100) while effectively managing global state. Performance issues arise when using the Material UI <TextField /> component, with noti ...

Transferring HTML content using jQuery AJAX and PHP

Can anyone help me with displaying the content of a division on one page to another? <div id="box-cont" class="box-content"> <?php echo $stat;// Includes multiple images and s ...

I have to make sure not to input any letters on my digipas device

There is a slight issue I am facing. Whenever I input a new transfer of 269 euros with the bank account number BE072750044-35066, a confirmation code is required. The code to be entered is 350269. https://i.stack.imgur.com/YVkPc.png The digits 350 corres ...

The children's className attribute can impact the parent element

As I work on creating a card object, I envision it with the className .card that is styled in CSS as follows: .card img{position:absolute; width:150px; height:160px} I want only the images inside my div to overlap each other while not affecting the divs ...

The issue of MUI components overlapping arises during window resizing

I am currently working on a chat component that includes both the chat display and message input fields. function Chat() { const chatBoxStyles = { bgcolor: "red", height: "70vh", mt: "1rem" }; const messageIn ...

The contact form is functioning properly on the local host, but it is not working on the

I am utilizing node and express to facilitate email sending via an html page. Here is the code snippet for my application: `const express = require('express'); const path = require('path'); const nodeMailer = require('nodemailer ...