Ways to restart script following Ajax call when additional search results are loaded

Implementing Klevu's search results page has been a manageable task so far. However, I encountered an issue where the search results page is displaying an Add to Cart button that should not be there, as confirmed by Klevu themselves. Their suggestion was to hide it using CSS, which led me to write this script:

<script>
window.addEventListener("load", () =>{
document.querySelectorAll('.kuProdAdditional').forEach(item => item.parentNode.removeChild(item));
})
</script>

Initially, this script worked flawlessly. But then, I was tasked with adding their infinite scrolling script into the head section, which was straightforward. However, now a new problem arises - the infinite scrolling feature triggers an Ajax call that loads subsequent pages along with the initial results. As a result, all results, including the original ones, display the Add to Cart button again. Essentially, I require assistance in ensuring that my script runs each time the Ajax call is completed.

The challenge lies in the fact that I lack the ability to modify the Ajax call to execute my script afterwards. Is there a method to detect when the page reloads so that I can run my script? While I am not a developer, I have been tasked with this IT-related assignment.

Answer №1

To monitor changes in the DOM, you can utilize a MutationObserver that observes the container for any modifications in its list of children.

const parentContainer = document.getElementById('parentContainer');
const addButton = document.getElementById('addButton');

addButton.addEventListener('click', () => {
  const newChild = document.createElement('div');
  newChild.innerHTML = 'New Child → <span class="kuProdAdditional">remove me</span> ← removed';
  parentContainer.appendChild(newChild);
});

const mutationCallback = (mutationsList, observer) => {
  for (const mutation of mutationsList) {
    if (mutation.type === 'childList') {
      parentContainer.querySelectorAll('.kuProdAdditional').forEach(item => item.remove())
    }
  }
};

const observer = new MutationObserver(mutationCallback);

observer.observe(parentContainer, {
  childList: true
});
.kuProdAdditional {
  /* ideally: 
  display: none;
  */
  background: red;
}
<div id="parentContainer">
  <div>Child 1</div>
  <div>Child 2</div>
</div>

<button id="addButton">Add Child</button>

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

Can $event be transferred from cshtml to Vue.component?

I am facing an issue when trying to pass an event into my Vue component. No matter what method I try, I keep getting a "TypeError: Cannot read property 'preventDefault' of undefined" error. Here is the code snippet for my Vue component: Vue.com ...

Encountering an issue with a Discord bot causing it to malfunction and deviate from its intended

Initially, everything appears to be functioning properly with the bot. When I execute the ?listen command, it responds correctly with bot is collecting messages now.... However, the ?stop command does not seem to have any effect. Furthermore, when I try th ...

What is the best way to retrieve all objects from this data model?

I am looking to collect all the Model Objects from the data structure provided below. const PRODUCTS = [ { brand: 'Audi', allSeries: { serie: 'A3', allModels: [ { model: ' ...

How to trigger the submission of a form within the submission event of another form using jQuery

I am encountering an issue with having two forms on a single page. Whenever I click on the submit button of the parent form, the parent form's submit event is triggered. In this event, I have included logic to submit the second form using the submit m ...

Encountering an error when trying to parse JSON response in an AJAX request, showing as

When I send an AJAX request to my GPS server, it returns JSON data in the following format if successful: {"result":[{"longitude":76.391529,"latitude":27.974347,"location":"Delhi-Ajmer Expressway - Madhosinghpura- Alwar - Rajasthan - India","speed":0,"dtt ...

Deciphering the intricacies of the http request

I encountered an issue while trying to send a POST request using jQuery AJAX. Upon making the request, I received the following error: XMLHttpRequest cannot load. Response for preflight has invalid HTTP status code 403 Now, I am unsure if the mistake i ...

Updating the $_GET parameter using JQuery when a button is clicked

I'm working on implementing a feature where a series of buttons can update the $_GET['year'] variable on my website. These buttons should function across different pages within my website, such as: example.com example.com/?search=foo exa ...

Enhancing the nested set structure by dynamically incorporating additional child nodes

My categories nested model includes subcategories, and I have set up a nested form to enable the creation of both categories and subcategories together in one form. Everything works smoothly if you pre-build the children in your new method like this: cla ...

Understanding the scope within a .when .done function in jQuery

I'm currently grappling with accessing a variable from within a .when.done function. Take a look at this illustrative example: var colviews = { 1: true, 2: true, 3: false } $.when( $.getScript( "/mckinney_images/jquery.tablesorter. ...

A guide on determining the return type of an overloaded function in TypeScript

Scenario Here is a ts file where I am attempting to include the type annotation GetTokenResponse to the function getToken. import { ConfigService } from '@nestjs/config'; import { google, GoogleApis } from 'googleapis'; import { AppCon ...

Continuing to use a function multiple times may lead to a type error as it is not a

My program is designed to be a quiz where users have to answer questions. After answering, they will see a summary and then get the option to submit or redo the questions. The issue arises when users choose to redo a question. Upon redoing it, the summary ...

Error: Node requires the use of 'import' to load ES modules

Here is the code snippet that I am currently working with: import { toString } from 'nlcst-to-string'; import { retext } from 'retext'; import retextPos from 'retext-pos'; import retextKeywords from 'retext-keywords' ...

When utilizing PHP and MySQL, the responses of Ajax requests consistently result in zero

Looking to fetch data from MySQL and display it in a div using AJAX PHP. The issue is that the ID field always shows as zero, even though it should auto increment. I've tried various methods like GET and POST but none seem to be working properly. &l ...

Creating a JavaScript/jQuery array containing values from multiple input fields

Having trouble figuring out a simple question. I want to create a JavaScript array of input values, but can't seem to get the code right. Below is the HTML: <input class="email" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

What is the best way to fetch the title property from my Campaign Contract for displaying it in the render method?

I'm currently working on a unique crowdfunding DApp that requires constant access to contract variables through function calls for retrieval purposes. The getDeployedCampaigns function is responsible for returning an array of deployed campaign addres ...

Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using: $("#item-container").append("<div class=\"panel col-md-2 ...

What is the reason behind JavaScript events causing a page refresh?

My code uses RegExp to search through an array of strings based on user input: Clinica.prototype.pesquisarDoente = function () { var exp = document.getElementById("pesquisaInput").value; var lista = document.getElementById("listaDoentes"); if ...

Retrieve the weekday dates for a specific year, month, and relative week number using Javascript or Typescript

I am in need of a custom function called getDaysOfWeekDates that can take a year, a month (ranging from 0 to 11), and the week number of each month (usually 4-5 weeks per month) as parameters, and return a list of dates containing each day of that particul ...

save function ajax failure

I have created a function that adds a row after confirmation. The issue is that after submitting, the tables do not reload and show an error alert. In reality, the data is successfully saved but I need to refresh the page for the table to reload. Below is ...

Retrieve data from a REST API in a dynamic manner without manually specifying the table structure in the HTML code

I am looking to retrieve JSON data via a post request from a REST API: http://localhost/post1 param1='1' The response will look like this: { "json_table": [ { "date": 123, "test": "hello2" }, { "date": 19, ...