Using jQuery trigger to activate a function whenever a new <li> element is appended to a <ul> list

I am currently facing an issue with a PHP page that utilizes flush() and ob_flush() to send progress updates to a browser. The page generates a styled <ul class="progresslog"> where individual

<li class="{success|warning|error}">
items are sent to the browser.

My goal is to hide successful notifications and only display errors. However, the current setup results in error messages getting lost among successful notifications. To address this, I plan to differentiate classes on <li> elements and use jQuery methods like .slideUp() and .slideDown() to show successes when requested by the user.

One challenge I face is that if there is no new information presented due to successful progress, users may assume there is no activity happening. To tackle this, I aim to have a summary link text dynamically update as more <li>'s get added to the list, showing something like 22 success notifications which will increase as output is delivered.

I already have a function to update the text within an <a id="progresslogtoggle"> element:

function updateProgress()
{
    var count = $('.progresslog .success').length;
    var warnings = $('.progresslog .warning').length;
    var errors = $('.progresslog .error').length;
    if (count > 0)
    {
        $('#progresslogtoggle').html ('Show ' + count + ' success notice' + (count != 1 ? 's' : '') + '. (' + warnings + ' warning' + (warnings != 1 ? 's' : '') + ' and ' + errors + ' error' + (errors != 1 ? 's' : '') + ' already shown)');
    }
    else
    {
        $('#progresslogtoggle').html ('There are no success notices to show! (' + warnings + ' warning' + (warnings != 1 ? 's' : '') + ' and ' + errors + ' error' + (errors != 1 ? 's' : '') + ' already shown)');
    }
}

Currently, I trigger the updateProgress() function once the list is complete and the final </ul> is added. But I want the link to update incrementally as items are added to the list. My attempt using

$('.progresslog').on ('change', updateProgress())
doesn't seem to work as expected.

If anyone has suggestions on how to resolve this issue, please let me know!

Update:

Here is a simplified version of the PHP code showcasing the problem:

echo "<a href=\"javascript:void(0);\" id=\"progresslogtoggle\">Please wait...</a></p>";
echo '<ul class="progresslog">';
// Include JS here, along with an initial call to the function.
for ($i = 0; $i < 1000; $i ++)
{
    // Some lengthy process that takes time
    sleep (1); // NOT REAL CODE!

    echo '<li class="';
    echo ($i % 5 == 0) ? 'warning' : 'success';
    echo '">Notice ' . $i . '</li>';
    flush ();
    @ob_flush ();
}
echo "</ul>";
echo "<script type=\"text/javascript\">updateProgress();</script>";

Disclaimer: I acknowledge the risks associated with manipulating an incomplete DOM structure, but I prefer not to delve into that discussion at this point.

Answer №1

Experiment with using MutationObserver to monitor changes in the childList of an ul element.

For more insights, check out this related post.

Answer №2

The change function is specifically designed for modifying input elements. To trigger a DOM change event, you can implement the following code:

$(".progresslog").on("DOMSubtreeModified", function() {
    alert("The list has been modified");
});

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

The presence of a border in CSS creates additional room around the content

My issue is that when I apply a border to a div, the content inside no longer fills up 100% of the width and height. I have already tried adding padding: 0;, margin: 0;, and box-sizing: border-box;, but the background still shows at certain zoom levels. ...

Creating an Angular table using reactive forms: a step-by-step guide

After reviewing the HTML snippet provided below, it is evident that there is a table with looping through mat cell using *matCellDef="let model". Inside each cell, there are input fields which are reactive forms. Each row or cell needs to have it ...

Learn the process of appending an item to a list using Vue.js

Recently starting with vue.js and facing an issue: data: { ws: null, newMsg: '', username: null, usersList: '' }, created: function() { var self = this; this.ws = new We ...

What is the most effective method to guarantee the creation of an object prior to navigating through the code that relies on it?

I recently encountered an issue with my code that utilizes fetch() to retrieve and convert .tiff images into an html5 canvas for display in a browser using tiff.js (https://github.com/seikichi/tiff.js/tree/master). While the functionality mostly works as i ...

[webpack]: npm ERROR! Call stack size limitation exceeded

While trying to install webpack using npm i -D webpack, an error is encountered as shown below. npm ERR! Maximum call stack size exceeded npm ERR! A complete log of this run can be found in: npm ERR! /Users/shobhuiy1/.npm/_logs/2019-02-05T10_31_29_46 ...

`Turn nested JSON into a formatted list using jquery`

I am currently facing two challenges: I am having trouble with the HTML structure, as shown in the image below Current HTML structure: https://i.stack.imgur.com/GH46J.png Desired HTML structure: https://i.stack.imgur.com/Dq3Gn.png How can I create d ...

Unraveling the Mystery of @Input and @Output Aliases in Angular 2

After researching about the @Input() and @Output() decorators, I discovered that we have the option to use an alias instead of the property name for these decorators. For example: class ProductImage { //Aliased @Input('myProduct') pro ...

What could be causing my external JavaScript file to not function properly upon loading my HTML file?

I have organized my code by separating the HTML and JavaScript portions. The JavaScript code is now in its own separate file and I use 'script' tags to reference it in the HTML file. Within the JavaScript code, I have two functions - one creates ...

Unique rewritten text: "Displaying a single Fancybox popup during

My website has a fancybox popup that appears when the page loads. I want the popup to only appear once, so if a user navigates away from the page and then comes back, the popup should not show again. I've heard that I can use a cookie plugin like ht ...

Embedding Facebook data into an HTML document

While I am able to retrieve data from Facebook and display it on the console, I am facing issues when trying to display it on an HTML page. I attempted using: $("#mydiv").text(data); or $("#mydiv").append(data); However, this displays [object Object] ...

Switch up the location of an object in Three.js by clicking the mouse

I'm attempting to replicate the click effect found on this particular website (enter and scroll in to witness the magic). The concept involves clicking on a picture, causing it to move front and center in front of the camera. Clicking it again sends i ...

The function Firebase.database() is unavailable in the Sails Service

I have developed a service named Firebase.js, and I am attempting to utilize it from my Controllers by using Firebase.database. However, I am encountering an error stating that Firebase.database() is not a function services/Firebase.js var admin = requir ...

What is the function of object-fit when used with the canvas element?

Despite my thorough search, I have not come across any documentation to clarify this issue. Is it possible to use object-fit cover on canvas elements? My experiments have yielded unexpected results so far. Could someone provide me with a conclusive answe ...

Executing a query in MongoDB to retrieve data from multiple collections simultaneously

Currently, I have two separate collections for different types of products. My goal is to retrieve all documents from both collections that belong to a specific user. I am aware that I could achieve this by running 2 queries for each collection, merging t ...

Unable to execute JavaScript within a partial view called through an AJAX request in MVC

In my partial view, I have written JavaScript code that retrieves the Geo-location of a client. <h1>Map</h1> <style type="text/css"> #map-canvas { height: 500px; } </style> <script type="text/javascript" ...

Navigating smoothly through different URLs to a single state using Angular's UI-Router

I recently started using angular's ui-router and I am looking for a way to configure multiple URLs to point to the same state. For instance: /orgs/12354/overview // should show the same content as /org/overview Currently, my $state provider is set u ...

Using jQuery to create a nested table

I have a table that I would like to customize so that when a user clicks on a row, only the child table under that specific row is visible while the child tables under other rows are hidden. How can I achieve this using jQuery? <table class="mainTabl ...

Steps to Transform String Array into Prisma Query Select Statement

I have a requirement to dynamically select Prisma columns based on client input: ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc'] The desired format for selection ...

AngularJS allows for the use of multiple `ng-views` on the homepage

As a beginner in Angular, I recently started using ngRoute and ngView directives. I have encountered an issue that I believe stems from my lack of experience in Angular. Here is the simplified markup on my index.html page: <html> <head> ...

The Power of Javascript in Enhancing Lightbox Experience

I am trying to enhance an image outputted by JavaScript with Lightbox functionality. Since the image link is dynamically created, I am approaching it this way! Despite searching on Stack Overflow, I have not found a solution that fits my needs... The cur ...