My global variable keeps getting caught by the addEventListener function

My script does not use jQuery and has an addEventListener on a button click. The issue is that after the first run, I want to change the value of "sendingurl" to something else. However, even though sendingurl is updated with the new id value, it doesn't change after the event is fired again. Instead, upon the second click, both the old and new events are triggered.

Console.log outputs:

  1. 1st click: event "click" is fired with url: input.php
  2. 2nd click:
    • event "click" is fired with url: input.php
    • event "click" is fired with url: update.php?io=items&id=693

I want to prevent the input from being triggered after the first click. Any solutions?

var itemid = getHash();
ini(prepare); // using window.onload to execute


function prepare() {
  if (itemid) {
    // update
    var sendingurl = 'update.php?io=items&id=' + itemid;
  } else {
    // input
    var sendingurl = 'input.php';
  }

  // submitevent
  æ($("submitBtn"), 'click', function() {
    console.log("event \"click\" is fired with url: " + sendingurl);
    var json = new FormData(document.forms[0]);
    ajax(sendingurl, json, submittedInput);
  });
}


// callback function after ajax did his magic
function submittedInput(response) {
  if (response) {
    if (!itemid) {
      itemid = response;
      prepare();
    }
  } else {
    $("status").innerHTML = "something went wrong with the input";
  }
}

// function to add events without the use of jquery or prototype
function æ(el, evType, fn, useCapture) {
  if (el.addEventListener) {
    el.removeEventListener(evType, fn, useCapture);
    el.addEventListener(evType, fn, useCapture);
    return true;
  } else if (el.attachEvent) {
    el.detachEvent('on' + evType, fn);
    var r = el.attachEvent('on' + evType, fn);
    return r;
  } else {
    el['on' + evType] = fn;
  }
}

Answer №1

When going through the code for the first time, there is no existing event handler to remove. As a result, your anonymous function gets added as an event handler. This anonymous function forms a closure, causing the value of sendingurl to remain "constant" regardless of any external changes to sendingurl. This explains why you keep getting the old value.

On the second run, the function passed to removeEventListener is not linked to any event yet since the second anonymous function is different from the one used in the first pass. Consequently, no event handler is removed. Instead, another event with the new anonymous function containing the updated value of sendingurl is added. This results in both functions being triggered.

To resolve this issue, consider converting your anonymous function into a regular function and use its designated name instead.

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

Step-by-step guide on making a post request to the Facebook Graph Api with Httparty in a Rails application

I'm currently working on developing a bot for Facebook Messenger, and I need to make a post request call to the Facebook Graph API. The sample code provided by Facebook is in Node.js, but I am working with Rails as my backend framework. Sample Code ...

Is selectpicker acting up?

Currently, I am troubleshooting a filter feature on a website that utilizes jQuery with JSON data. Everything was functioning properly until recently when an error started appearing: The selectpicker function is not recognized I would greatly appreciat ...

Can someone show me how to code a function that transforms my paragraph into an image when I hover over it?

< p id="p1" onmouseover="this.style.color='transparent';flipPara()"> < p id="p2" onmouseover="spookyPara()"> function spookyPara() { document.getElementById("p1").attribute = "All_Images/ghost.png"; } I currently have this code sn ...

A guide on changing JSON into a JavaScript array

I have a JSON data string that needs to be converted into a JavaScript array. Here is the JSON data: [["Claim","1"],["issue","4"]] My desired output: var data = new google.visualization.DataTable(jsonData); data.addColumn('string' , & ...

Building responsive grids in React using Material-UI components

https://i.sstatic.net/d2CIo.png On the left side, there is a map with controls, and on the right side, there are fields displaying the last update, a table, and an input field. I am looking to create a responsive design where when it reaches a certain si ...

When working with TextareaAutosize component in MUI, an issue surfaces where you need to click on the textarea again after entering each character

One issue that arises when using TextareaAutosize from MUI is the need to click on the textarea again after entering each character. This problem specifically occurs when utilizing StyledTextarea = styled(TextareaAutosize) The initial code snippet accompl ...

Verify whether the cookie information is in an array format

As visitors click on products on my site, I am storing their IDs in a cookie. Each click adds the new ID to an array stored in the cookie. This is how I set up the cookie and its current value after a few clicks: var cookieArray = []; cookieArray.push( ...

Exploring the dynamics of Django, Webpack, and Vue with the added feature of code splitting: A guide to customizing chunk

I am currently using Django in conjunction with Webpack and Vue, as well as implementing Code splitting within Webpack. The issue I am facing is that Webpack splits chunk files from the source code of .vue files, but I am unable to load these chunk files i ...

Tips for successfully sending a nested function to an HTML button and dropdown menu

I'm working on two main functions - getChart() and fetchData(). The goal is to retrieve chart data and x/y axes information from a database. Within the getChart function, I'd like to incorporate a dropdown menu for displaying different types of c ...

Create a mechanism in the API to ensure that only positive values greater than or equal to 0 are accepted

My goal is to process the API result and filter out any values less than 0. I've attempted to implement this feature, but so far without success: private handleChart(data: Object): void { const series = []; for (const [key, value] of Object.e ...

Navigate to the editing page with Thymeleaf in the spring framework, where the model attribute is passed

My goal is to redirect the request to the edit page if the server response status is failed. The updated code below provides more clarity with changed variable names and IDs for security reasons. Controller: @Controller @RequestMapping("abc") public clas ...

Retrieve the value of each element within the elements array

I need help retrieving values from elements within an array. Specifically, I am looking to extract the value of the <span id="attendees"> element within each <a> element. For example: HTML: <a id="meetingItem_{{meeting.id}}" onclick="Auth ...

What is the correct way to display or hide a button based on my specific situation?

Creating a 'show more' button for my app has presented me with a challenge. I am using a directive to handle actions when the user clicks on the read more button: (function(window, angular) { var app = angular.module('myApp'); ...

Tips for inserting the <a> HTML tag into a JSON array object

I am relatively new to creating array objects and I am unsure on how to add a link within a <a> tag in a JSON file. Here is the JSON object code: powerUpList: [ { id: 8, name: 'Automate your API column type ', description: & ...

Dynamic JavaScript Animation

Check out this code snippet I currently have. Notice how the text seems to jump when rerun? Give it a try and see for yourself. The big question is: How can this be fixed? $("#aboutUsText").delay(1000).fadeOut(1000) $("#aboutUsText").attr("MyState", "1") ...

Tips for displaying the sum of a grouped field in the balloonText using Amchart

I recently started working with Amcharts and I am seeking advice on what I may be doing incorrectly. Below is the snippet of my JavaScript code: var chartData1 = []; generateChartData(); function generateChartData() { var month = new Array( ...

turning every input field's border to red if none of them were filled out at least once

I struggle with javascript and need some help. I have a form with multiple input fields, and I want to ensure that the user fills in at least one of them. I found code that triggers an alert message if the user does not fill in any fields, but I would pref ...

Ways to automatically style the child divs within a parent div

I'm trying to figure out how to float a parent div with child divs of different widths and heights while maximizing the use of space and not being affected by absolutely positioned elements. For reference, here's an example: http://jsfiddle.net ...

What is the best method for inserting a line break into a string?

Can you please explain how I can insert a line break into a string with JavaScript? I have tried using the <br/> tag, but it's not working. What is the correct way to achieve this? JavaScript var str="Click Here" +"<br>"+ "To Set" +"< ...

Determine the scroll percentage of an element using jQuery

My goal is to create a div that animates from 0% - 100% based on the percentage of an element scrolled. I have defined some variables, but I am struggling with calculating the height as a percentage. Setting the initial width and detecting scroll are str ...