Increment the counter value by one when a new class is created or appended

My goal is to develop a system that increments the 'fault' counter by one every time a wrong answer is submitted. To achieve this, I have configured my system to detect when a class named "incorrectResponse" is generated. However, I am encountering an issue where the counter only increases upon page load and does not update afterwards.

Below is the code snippet that I have attempted but hasn't been successful:

  //*-- Fault counter --*//
  if (document.querySelectorAll('incorrectResponse')) {
    $('#fault-counter').html(function(i, val) { return val*1+1 });
  };

Can anyone shed light on why this behavior is occurring?

Answer №1

If you are utilizing jQuery (as mentioned in your comments), one approach could be to add an event listener to the container where your 'wrong answers' are located.

A custom event would be manually triggered each time a wrong answer is added to the page, allowing the event listener to update the count of incorrect answers accordingly.

function updateNumberOfIncorrectMsgs() {
  $('.counter').text($('.incorrectAnswer').length);
}

updateNumberOfIncorrectMsgs();
var $container = $('.wrongAnswersContainer')
  .on('newWrongAnswerAdded', function() {
    updateNumberOfIncorrectMsgs();
  });

// The for loop and setTimeout are used to simulate new messages being added to the page, while the crucial part is the custom event that is triggered upon adding an element.
for (var i = 1; i < 6; i++) {
  setTimeout(function() {
    $container
      .append('<p class="incorrectAnswer">Incorrect answer</p>')
      .trigger('newWrongAnswerAdded');
  }, 1000 * i);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Number of incorrect answers: <span class="counter"></span>
</p>
<div class="wrongAnswersContainer"></div>

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

Is there a way to implement a setTimeout delay in my puppeteer browser?

I wrote a function named waitForTimeout to introduce a brief delay that can be awaited once the browser navigates to a new page. function waitForTimeout(timeout) { return new Promise((resolve) => { setTimeout(resolve, timeout) }) } const puppet = () =& ...

Load and execute a dynamically created script in JavaScript at the same time

I am exploring the option to load and evaluate a script from a third-party synchronously. Here is an example that currently works well: <head> <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

What is the optimal approach for managing script initialization on both desktop and mobile devices?

I have implemented a feature on my website that can detect whether the viewer is using a mobile device. Additionally, I have created a JavaScript script that adjusts settings based on whether the user is on a mobile device or not. However, I am wondering ...

Looking to simplify the complex JSON structure by converting it into an array using JavaScript

Being a newcomer to javascript, I am struggling with breaking down a complex structure into an array. The current structure is as follows: [ { "Key": "ProducePRINKA0370001", "Record": { "docType": "Produce", "PR ...

Understanding the scope of a variable within a function in JavaScript

Working with JSON, I am attempting to determine the total number of elements in the response. $.getJSON("/api/getEvents", function(data) { $.each(data, function(key, event) { var count = 10; $.getJSON("/api/getUsers", f ...

Resizing images in HTML can sometimes lead to extra white space appearing underneath the

I am facing an unusual scaling issue with my website design. Whenever I resize the browser window horizontally, the image scales correctly, but it leaves a white space below it where the rest of the page should start from if the window is large. I'm ...

What methods are available to stop Internet Explorer from caching HTML content without resorting to utilizing arbitrary query parameters?

To avoid caching HTML on postbacks in Internet Explorer, we are currently utilizing random query strings, but our goal is to transition to URL re-writing. Removing these random parameters would be ideal. What is the recommended approach for resolving this ...

When a specific function is called, the DayPickerRangeController in the airbnb/react-dates library will update the

Is it possible to dynamically set the visible month in DayPickerRangeController after the component has been rendered? I have a 'handleMonthChange' function that I want to use to change the visible month, but setting 'initialVisible' mo ...

The latest update of MS CRM 2013 now includes a version number for WebResources that are of script

I came across an unusual issue in MS CRM 2013 that seems to be intentional, and I need some assistance in finding a workaround for it. The problem is that calling the getScript jQuery method from a WebResource is not possible. In CRM, a version string is ...

Which hook should be implemented for automatically updating stock levels after a successful payment on WooCommerce?

When working with WooCommerce, I have implemented my own custom payment method using javascript code. I have successfully retrieved the total amount and passed it to my payment system using the following PHP code: <?php $GLOBALS['cart_total'] ...

Using JavaScript to filter an array of objects by another array of objects

My collection of messages includes oldMessages = [ {id:1,message:'message_A'} , {id:2,message:'message_B'} ] and another set as newMessages = [ {id:1,message:'message_A'} , {id:2,message:'message_B'} , {id:3,mess ...

Displaying a div and ensuring it remains visible upon clicking

$(document).ready(function() { $('#input').focusin(function() { if ($(this).val() != '') { $('#div').show(); } else { $('#div').hide(); } $('#input').keyup(function() { / ...

I am experiencing an issue with importing my CSS file

Have a somewhat confusing HTML question that is frustrating me. I am struggling to incorporate certain css files into a jsp page. Here is what I have attempted: <link href="<c:url value="/css/bootstrap.css"/>" rel="stylesheet"> And also tri ...

Unable to retrieve an image from various sources

My setup includes an Express server with a designated folder for images. app.use(express.static("files")); When attempting to access an image from the "files" folder at localhost:3000/test, everything functions properly. However, when trying to ...

"Encountered an issue when attempting to convert undefined or null to an object within a

I am facing an issue with my test setup which looks like this: var jsdom = require('jsdom').jsdom; var document = jsdom('<html></html>', {}); var window = document.defaultView; global.jQuery = global.$ = require('jquer ...

AngularJS is failing to properly register custom directives

Looking to enhance the SEO caching capabilities of my AngularJS website, I've embarked on implementing a couple of directives for custom page titles and descriptions. Incorporated within my app config (angular.module('website', [...'we ...

Received an unexpected result while attempting to access information from a node API

Recently, I attempted to utilize the fetch() method within the componentDidMount() method in my React App. Surprisingly, it worked perfectly on Postman and successfully retrieved data from the specified URL. Below is a snippet of the code from my React A ...

Can you provide any methods for enhancing a pre-existing jQuery event handler?

I have developed a code that resets the form and clears it each time the reset event occurs like this: $("form").on("reset", function(event) { event.preventDefault(); $("form").clearForm(); $("#reportGenerated").empty(); }); This code is stor ...

Despite having a result, the Promise is returning an undefined value

In Vuejs, I have a method named getUsers that takes an array as input and fetches user data from the database. When calling it like this, it successfully returns the results: this.getUsers(executives).then( result => { this.speci ...

What is the best way to transform a CSS linear gradient into JavaScript code for use in a React Native application

Struggling to convert my input data from Figma CSS into a format that works with react native. Are there any helpful libraries for this task? If so, how should I go about writing it out? The CSS code in question can be found here. ...