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

How do I go about showing every character on a separate line using a for loop?

var input = prompt("What is Lance attempting to convey?"); //user enters any text for (var i = 0; i <= input.length; i++) { var output = input.charAt(i); if (output == "e" || output == "o" || output == "a" || output == "u") { outp ...

Optimal approach for managing numerous modals containing map data in Next.js

Hey there, I'm facing an issue while trying to utilize map data in conjunction with modals. Although I have set the state for all modals, when I use an array object within the map data, the modals end up showing duplicated. To provide clarity, let me ...

Is there a way for me to store the output of an AJAX call?

One of the challenges I'm facing involves an AJAX request: $.ajax({ url: 'script.php?val1=' + value1 + '&val2=' + value2, dataType: "json", success: function (data) { var newValue1 = data[0]; ...

Creating a form submission event through Asp.net code behind

Is there a way to change the onsubmit parameter of a form in an asp.net project, specifically from the master page code behind of a child page? I am interested in updating the form value so that it looks like this: <form id="form1" runat="server" onsu ...

It seems that Firefox is ignoring the word-wrap style when the class of a child element is changed

Take a look at this: var iconIndex = 0; var icons = ['check', 'chain-broken', 'flag-o', 'ban', 'bell-o']; $('button:eq(0)').click(function() { iconIndex = (iconIndex + 1) % icons ...

Troubleshooting my HTML5 local storage issues for optimal functionality

I've been working on using HTML5's localstorage to save two variables and load them upon page refresh, but I seem to be encountering some issues when trying to load the saved items: Variables in question: var cookies = 0; var cursors = 0; Savi ...

Exploring the Variance between 'npm run serve' and 'npm run dev' Commands in Vue.js Development

Can you explain to me the distinction between npm run serve and npm run dev in vuejs? Additionally, can you clarify why it is recommended to use the npm run serve command when running a project? ...

I encountered an issue with adding a console log in the getStaticProps() function that resulted in the error: SyntaxError: Invalid Unicode escape sequence at eval (<anonymous>

Welcome to my users.js page! import React from 'react' const displayUsers = ({users}) => { return ( <> { users.map(user => { return <div key={user.id}> {user.name} </div> }) } </&g ...

Is it possible to identify the form triggering the ajax call within a callback function?

There are multiple forms on my website that share the same structure and classes. The objective is to submit form data to the server using the POST method, and display an error message if any issues arise. Here's how the HTML code for the forms look ...

Breaking up an array into smaller chunks with a slight twist

Here's a straightforward question. I have an array, like this: let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxChunkLength = 3; I am looking to divide this array into multiple arrays as follows: [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, ...

Error encountered: Attempting to render an object as a react component is invalid

I am attempting to query data from a Firestore database. My goal is to retrieve all the fields from the Missions collection that have the same ID as the field in Clients/1/Missions. Below, you can find the code for my query: However, when I tried to execu ...

how to transfer data from backend servlet to frontend javascript

Hey, I'm still learning about servlets so please excuse any confusion in my message! So basically, I'm trying to figure out how to pass a value from a servlet to JavaScript or even retrieve values from a servlet method within JavaScript. But I&ap ...

Conceal the .dropdown-backdrop from bootstrap using solely CSS styling techniques

Is there a way to hide the .dropdown-backdrop element from Bootstrap for a specific dropdown on a webpage using only CSS? I found a solution that involves Javascript, you can view it on JSFiddle here. However, I am hoping to achieve this without relying o ...

Can someone assist me with navigating through my SQL database?

Struggling with a script that searches multiple fields in the same table, I need it to return results even if one or three parameters are left blank. My attempts using PHP and MySql have been fruitless so far, which is why I am reaching out to the experts ...

Images not showing in Vue.js

I have been working on setting up a carousel using bootstrap-vue. It is being generated dynamically through an array containing three objects with keys such as id, caption, text, and image path. The issue I am facing now is that while the caption and text ...

Relaunch node.js in pm2 after a crash

Based on this post, it seems that pm2 is supposed to automatically restart crashed applications. However, when my application crashes, nothing happens and the process no longer appears in the pm2 list. Do I need to enable an 'auto restart' featu ...

How to effectively pass custom props or data to the Link component in Next JS

As I dive into Next JS, I've hit my first roadblock. Currently, I am working on a page that showcases various podcast episodes with preview cards on the homepage. The card component code looks like this: import React from 'react'; import Li ...

Achieve uninterrupted deployment of node.js applications by utilizing naught for zero downtime implementation

Recently, I began utilizing naught for deploying my node.js applications (https://github.com/andrewrk/naught). In my Ubuntu Server, I have a directory that contains my node.js (express) app. To deploy it, I used the command "naught start app.js" from tha ...

Webpack has successfully built the production version of your ReactJS application. Upon review, it appears that a minified version of the development build of React is being used

Currently, I am implementing Reactjs in an application and the time has come to prepare it for production. In my package.json file, you can see that there is a "pack:prod" command which utilizes webpack along with a specific webpack.config.js file to build ...

Steps to ensure that a particular tab is opened when the button is clicked from a different page

When I have 3 tabs on the register.html page, and try to click a button from index.html, I want the respective tab to be displayed. Register.html <ul class="nav nav-tabs nav-justified" id="myTab" role="tablist"> <l ...