The issue persists with the addEventListener function not working multiple times

My issue is that the addEventListener function is only working for the 'scroll' event and not for 'addMoreFields' or 'removeFields'. If I move the scroll section down, then it works for 'addMoreFields' and 'removeFields', but no longer works for 'scroll'.

const wraping = document.querySelector('#Wraping');
const addMoreFields = document.querySelector('#btn-add');
const removeFields = document.querySelector('#btn-remove');
let inpName = 0;
const scroll = document.querySelector(".scrollToTop");

scroll.addEventListener("click", function(){
  window.scrollTo({
    top: 0,
    left: 0,
    behavior: 'smooth'
  });
});


addMoreFields.addEventListener("click", function(){
  let input_tags = wraping.getElementsByTagName('input');
  if (input_tags.length < 10){
    inpName = inpName + 1;
    let newField = document.createElement('input');
    newField.setAttribute('type','text');
    newField.setAttribute('name','products[' + inpName + ']');
    newField.setAttribute('class','spacing form-control');
    newField.setAttribute('placeholder','Enter product URL_' + (inpName + 1));
    wraping.appendChild(newField);
  }
});

removeFields.addEventListener("click", function(){
  let input_tags = wraping.getElementsByTagName('input');
  if(input_tags.length > 1){
    wraping.removeChild(input_tags[(input_tags.length - 1)])
    inpName = inpName - 1;
  }
});

HTML

<div class="mb-3">
   <label class="form-label">Monetization</label>
   <div id="Wraping">
     <input class="spacing form-control" placeholder="Past product URL" type="text" name="products[]">
   </div>
   <button id="btn-add" class="c-button compose-btn btn " type="button" name="add">Add</button>
   <button id="btn-remove" class="c-button compose-btn btn " type="button" name="remove">Remove</button>
</div>

Answer №1

When using addEventListener, make sure to pass a function reference as the second parameter. Avoid calling the function directly within the addEventListener method. Try this updated code snippet:

document.addEventListener('DOMContentLoaded', function () {
alert("document loaded!");
sliderRed.addEventListener("change", function(){alert(sliderRed.value)} );
// function wrapped properly

} );

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 can I retrieve a Jquery tooltip from a HiddenField?

I am trying to utilize a hidden field in my asp.net calendar to display a message using JQ Tooltip. However, when I attempt to use the value of the HiddenField for the tooltip, I encounter an error. $("#hf_taskID_cal").tooltip($("#hf_taskID_cal").val()); ...

Is it possible for me to design a unique path without relying on redux?

I am working on a Loginscreen.js component import React, { Component } from 'react'; import Login from './Login'; class Loginscreen extends Component { constructor(props){ super(props); this.state={ username:'&apo ...

Is it possible to transform a .csv document into a JavaScript array with dictionaries? Each dictionary's keys would correspond to the column headers in the .csv file, and the values would be the

Let's imagine a scenario where I have a .csv file with the column headers listed in the first row, and their respective values are provided in the subsequent rows as shown below: index,id,description,component,service 0,5,lorem ipsum,7326985,Field Ser ...

What methods can be used to construct components using smaller foundational components as a base?

Is there a more elegant approach to constructing larger components from smaller base components that encompass common functionalities, akin to an interface in the OOP realm? I'm experimenting with this concept, but it feels somewhat inelegant. Repor ...

What is causing jQuery toggleClass to fail in removing a class?

I have successfully implemented a Skills accordion feature, but I am now trying to add a button that toggles all the skill sections at once. However, I am facing issues with jQuery not correctly adding or removing classes on the .accordion-trigger-all elem ...

Lambda function failing to execute Auth0 methods through the Auth0 node-auth0 SDK

I am working with a lambda function that triggers when a message is added to the SQS queue. Within the message, there is a userId that I want to connect to using the Auth0 node SDK. The code snippet for my GetUserDetails function below shows that it logs ...

I encountered an error in my Node application while attempting to use Sequelize, specifically a TypeError where it was unable to read the property '

I encountered the following error message while attempting to implement user authentication using passport-local and sequelize with MySQL. The server creates a new table in SQL if it doesn't exist, but when I click on the sign-up button, an error occu ...

A fresh javascript HTML element does not adhere to the css guidelines

While attempting to dynamically add rows to a table using Javascript and jQuery, I encountered an issue. Here is my code: <script> $(document).ready(function(){ for (i=0; i<myvar.length; i++){ $("#items").after('<tr class="item- ...

Dealing with Vue's performance problems when using input type color and v-model

I am encountering a problem with setting the v-model on an input of type color. Whenever I change the color, there is a noticeable drop in frame rate and the application's FPS spikes from 60 to 3. You can see it reflected in the Vue performance graph ...

The backend and frontend both operate smoothly individually, so why is it that the frontend is unable to load backend data on Vercel

Today, I deployed both my frontend and backend on Vercel. Before this, there was an error (not 404) in the backend. However, after someone on Stack Overflow suggested changing the root file from server.js to index.js, I made the change and the backend star ...

Having trouble accessing the property 'top' of an undefined object in your Ruby on Rails project?

After thoroughly reviewing all the similar threads on SO regarding this error, none of them provided a solution that worked for me. Here is the flow of events: Go to the new Customer page, fill out the required fields, and click save Invoke a method in ...

Discover the joy of reading with wrap/unwrap to consume more content in less

I am experimenting with a 'read-more read-less' feature using a wrap method that currently only works for the 'show more' functionality. So, to clarify, if the text exceeds a certain length, I truncate it and insert a read-more-link ( ...

Objects of equal nature combine and sift through

I am looking to categorize objects based on their status ID and also retrieve data and CSR counts for each item. Each StatusName has multiple items: [ { "StatusId": 2, "StatusName": "ordered", " ...

Ways to display form choices that are influenced by other form selections

In my form, the user is supposed to choose a specific item at the end. As they fill in the initial options, the subsequent fields below change dynamically. Here is an example: Type: { t1:{ Number of X:{ 1:{...} 2:{...} ...

Issue with running the Jquery each function within a textbox inside an ASP.NET gridview

Below is the gridview markup: <asp:GridView ID="gvDoctorVisits" runat="server" DataKeyNames="AdmissionId" class="tableStyle" AutoGenerateColumns="False" Width="100%" EmptyDataText=& ...

The Limits of JavaScript Tables

Currently facing an issue with a webpage under development. To provide some context, here is the basic layout of the problematic section: The page features a form where users can select from four checkboxes and a dropdown menu. Once at least one checkbox ...

Utilizing Props in React to Slice and Dice Data Within a Separate Component

Currently, I am in the process of creating an about text for a profile that will include an option to expand or collapse based on its length. To achieve this, I am utilizing a function from the main home component: <AboutText text={aboutData}/> Abo ...

Is the 404 error a result of the ajax code?

I'm currently working on a form that utilizes AJAX to validate and interconnect various form elements. Below is a simplified version of my code: <?php if( isset( $_POST['create_transaction'] ) ) { // do something } ?> <div> ...

Error while retrieving reference from mongoDB in NodeJS

I am currently working on a small website that needs to query my local mongodb. Everything works perfectly fine on localhost. That's why I decided to begin with NodeJS. While all JavaScript functions work seamlessly when run separately, I encounter a ...

Executing asynchronous methods in a Playwright implementation: A guide on constructor assignment

My current implementation uses a Page Object Model to handle browser specification. However, I encountered an issue where assigning a new context from the browser and then assigning it to the page does not work as expected due to the asynchronous nature of ...